for loop with findCorrelation function from the caret package in R

Viewed 15

please have look at the following code:

my_list <-list()

for (i in seq(0.1,0.9,0.1)) {
  correlationsMatrix <- cor(mtcars, method = 'spearman', use = "pairwise.complete.obs")
  highCorFeatures <- findCorrelation(correlationsMatrix, cutoff = i, exact = TRUE)
  my_list[[i]] <-highCorFeatures
}

I try to get a list back with different cut off values. But the error "Error in my_list[[i]] <- highCorFeatures : attempt to select less than one element in OneIndex " appears. Any idea how to get this done ? Thank for your help.

1 Answers

You can use seq_along:

library(caret)

my_list <-list()

cutoffs = seq(0.1,0.9,0.1)

for (i in seq_along(cutoffs)) {
        correlationsMatrix <- cor(mtcars, method = 'spearman', use = "pairwise.complete.obs")
        highCorFeatures <- findCorrelation(correlationsMatrix, cutoff = cutoffs[i], exact = TRUE)
        my_list[[i]] <-highCorFeatures
}
Related