I have a few dataframes with only a few variables different from each other. Mostly they are the same. I would like to prepare the variables in a loop, so I do not have to specify each and every variable for all my dataframes separately. I'm however running into some issues.
clist <- c("data", "data_error", "data_RT")
I first made a list of the names of my dataframes
for (i in clist) {
i$ID <- as.factor(i$ID)
i$TMS <- as.factor(i$TMS)
i$bias<- as.numeric(i$bias)
... }
The I try to loop over all the variables I want to prepare. This is however not possible and I get an error message saying:
Error in i$ID : $ operator is invalid for atomic vectors
I tried google for help, but I did not understand the explanations for it :( Could you help me understand what I'm doing wrong and how I could solve it?
You could use a list of dataframes instead of a vector of names:
clist <- list(data, data_error, data_RT)
Then loop through the list:
for (i in 1:length(clist)) {
clist[[i]]$ID <- as.factor(clist[[i]]$ID)
clist[[i]]$TMS <- as.factor(clist[[i]]$TMS)
clist[[i]]$bias<- as.numeric(clist[[i]]$bias)
... }
Afterwards, you can use
list2env(clist,globalenv())
to put the dataframes back into your global environment. I would advise you to just keep them inside the list, though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.