2

I have the following data frame, Test_for_loop.csv

I want to separate the data frame based on the column "mycoreLabel". So, i used the function list2env() and it worked properly. Now for each dataframe i want to get the mean of column 'splineBD'. I want ot use for loop. But when I using the following script it's giving me the following error,

"Error: $ operator is invalid for atomic vectors"

This is the code i have used,


list2env(split(Core_strata_OC, Core_strata_OC$mycoreLabel), envir = .GlobalEnv)

OCi<- c()
for (i in 1:3){

  OCi[i]<- mean(`i`$splineBD)
  OCi
}
OCi<-as.data.frame(OCi)

  • This looks like an XY problem to me. It looks like you want to do some group-level calculations on your data set. Perhaps you can try reading this question and the answers to see what makes sense for you: https://stackoverflow.com/questions/21982987/mean-per-group-in-a-data-frame – MichaelChirico Jun 16 '20 at 16:19
  • @MichaelChirico Thanks for your reply. But i want to specifically use a for loop here. It work perfectly if the dataframe name is not numeircal but i want to use the list2env() to get dataframe with numerical names and use loop to work with those data frames – Mohammad Murad Jun 16 '20 at 16:24
  • `i` is an atomic vector (of integers), and `$splineBD` is an attempt to access a named element, but `i` isn't a list, and its elements don't have names, hence `$ operator is invalid for atomic vectors`. – webb Jun 16 '20 at 16:25
  • @webb Thanks. How can I solve this? Should I convert 'i' to a list before the line for obtaining the mean? – Mohammad Murad Jun 16 '20 at 16:32
  • the point of the linked answer is that they are in effect _doing the `for` loop for you_ – MichaelChirico Jun 17 '20 at 02:13

1 Answers1

0

You should probably skip list2env and instead do something like this:

Core_strata_OC_list = split(Core_strata_OC, Core_strata_OC$mycoreLabel)

OCi<- c()
for (i in 1:3){

  OCi[i]<- mean(Core_strata_OC_list[[i]]$splineBD)
  OCi
}
OCi<-as.data.frame(OCi)
webb
  • 4,180
  • 1
  • 17
  • 26