0

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?

3
  • 1
    The $-operator doesn't work dynamically. Use i[,"ID"] <- as.factor(i[,"ID"]) .... Commented Sep 26, 2017 at 11:02
  • 1
    also you need the dataframes in clist as object_names and not as strings. Commented Sep 26, 2017 at 11:04
  • Hi Andre! Thanks for the hint! It however still produces an error. I changed it now to: clist <- c(data, data_error, data_RT) for (i in clist) { i[,"ID"] <- as.factor(i[,"ID"]) } but it tells me Error in [.default(i, , "ID") : incorrect number of dimensions. This confuses me, because if I just replace the "i" with "data" (as I intend the loop to do) data[,"ID"] <- as.factor(data[,"ID"]), it does work... Any thoughts on where the dimension mismatch might stem from? Commented Sep 26, 2017 at 11:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.