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")
}  
Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
abhi
  • 53
  • 9
  • Create a list and use `lapply` to chnage names: `lapply(list(df1, df2, df3), function(x) { names(x) <- paste0("var", 1:3); x })` – markus Mar 10 '19 at 22:41
  • 1
    @markus or use `setNames(x, paste0("var", 1:3))` and avoid returning object at end. – Parfait Mar 10 '19 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? – abhi Mar 10 '19 at 23:53
  • @abhi post another question whit an short example showing the problem – Robert Mar 11 '19 at 11:15

1 Answers1

1

Try using a list instead

dfl=list(df1,df2,df3)
  for(i in 1:length(dfl)) {
    colnames(dfl[[i]])<-c("var1","var2","var3")
  }
Robert
  • 5,038
  • 1
  • 25
  • 43
  • 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? – abhi Mar 10 '19 at 23:38
  • Same answer: use a list instead. [Reading this would probably be good for you](https://stackoverflow.com/a/24376207/903061). – Gregor Thomas Mar 11 '19 at 03:21