0

I am using the following code to access data frames df1,df2 and df3 in a loop and rename them. This gives me an error. How do I tell R that its a data frame not a

for(i in c(df1,df2,df3)) {
  colnames(data.frame(i))=c("var1","var2","var3")
}  
4
  • Create a list and use lapply to chnage names: lapply(list(df1, df2, df3), function(x) { names(x) <- paste0("var", 1:3); x }) Commented Mar 10, 2019 at 22:41
  • 1
    @markus or use setNames(x, paste0("var", 1:3)) and avoid returning object at end. Commented Mar 10, 2019 at 23:31
  • Thanks for the answer. Also, when my function is passing a string let's say "count" and I want to create multiple variables using it in the function, like a_count b_count c_count how do I proceed? Commented Mar 10, 2019 at 23:53
  • @abhi post another question whit an short example showing the problem Commented Mar 11, 2019 at 11:15

1 Answer 1

1

Try using a list instead

dfl=list(df1,df2,df3)
  for(i in 1:length(dfl)) {
    colnames(dfl[[i]])<-c("var1","var2","var3")
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. Also, when my function is passing a string let's say "count" and I want to create multiple variables using it in the function, like a_count b_count c_count how do I proceed?
Same answer: use a list instead. Reading this would probably be good for you.

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.