RStudio使用kohonen包构建SOM模型时遇对象未找到等错误求助
Let’s break down your issues one by one—these are super common pitfalls when starting out with self-organizing maps in R, so you’re not alone!
The Root Cause: You’re Relying on R’s Built-in data Function
Your first error is the domino that causes all the others:
Error in data[, c(2, 4, 5, 8)] : object of type 'closure' is not subsettable
data is a built-in R function (used to load pre-packaged datasets), not your custom dataset. You forgot to load or define your own data, so R tried to treat the data() function like a dataset—which doesn’t work.
Step-by-Step Fixes
Let’s rewrite your code with corrections that address every error:
Load Your Actual Dataset First
Replace the genericdatawith your real dataset. For example, if your data is in a CSV:# Load your data (update the file path to match your file) my_custom_data <- read.csv("your_data_file.csv")If your data is already in your R environment, use its actual name instead of
my_custom_data.Create Your Training Subset
Now use your named dataset to builddata_train:require(kohonen) # Use your actual dataset name here data_train <- my_custom_data[, c(2,4,5,8)]Generate the Scaled Matrix
Withdata_trainproperly created, this line will run without missing object errors:data_train_matrix <- as.matrix(scale(data_train))Train the SOM and Visualize Results
The rest of your code will work now that all prerequisite objects exist:som_grid <- somgrid(xdim = 20, ydim=20, topo="hexagonal") som_model <- som(data_train_matrix, grid=som_grid, rlen=500, alpha=c(0.05,0.01), keep.data = TRUE ) plot(som_model, type="changes")
Why the Tutorial Code Worked
Tutorials almost always assume you’ve already loaded a dataset named data (or they explicitly define it in the example). You skipped that critical step of loading your own data and accidentally used R’s built-in data function instead.
内容的提问来源于stack exchange,提问作者caroline

