I apologize if this question seems rudimentary. I’m a bit unclear on if it’s possible / how to use for loops with a list of data frames in R.
I have dataframes that are subsets of a larger dataframe:
billysuzy <- subset(userlist,user1 %in% c("billy","suzy"))
joefrank<- subset(userlist,user1 %in% c("joe","frank"))
georgelenny <- subset(userlist,user1 %in% c("george","lenny"))
I would like to loop through and find correlation values for the same variables (time and simscore) for each subset.
cor(time, simscore)
However, I am quite uncertain how to structure such a for loop and unsure how to structure a function to attach and detach within lapply.
I was thinking:
somelist <- list(billysuzy, joefrank, georgelenny)
with lapply:
corz <- lapply(somelist, function(df) detach(), attach(df),cor(time, simscore))
lapply(corz, print)
or with for:
for (i in 1:length(somelist)){
detach()
attach(somelist[i])
cor(time, simscore)
}
I apologize for offending anyone’s R sensibilities or if the seems like two questions – the answer is any which describes how to do the one thing i.e. loop through the dfs in the list and find there corr values.
I would really recommend avoiding
attachanddetach.You could try something like this
Or
Or