I am trying to change the variable names in all data frames in a for loop. Any example of the data is:
df1 <- data.frame(
Number = c(45,62,27,34,37,55,40),
Day = c("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"))
df2 <- data.frame(
Number = c(15,20,32,21,17,18,13),
Day = c("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"))
df3 <- data.frame(
Number = c(12,32,22,14,16,21,30),
Day = c("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")
L <- list(df1,df2,df3)
My current attempt is:
for(i in L){
colnames(L) <- c("NewName1", "NewName2")
}
Which is not working, I do not understand why it is not working. Please let me know if someone can guide me in the right direction.
for (i in L), then you need to useiinside the loop. In this case, you're better off using integer indexes to loop over:for(i in seq_along(L)){colnames(L[[i]]) = c("NewName1", "NewName2")}.applyis not faster thanfor loop. The "applyfunction has a for loop in its definition. Thelapplyfunction buries the loop, but execution times tend to be roughly equal to an explicitfor loop" (burns-stat.com/pages/Tutor/R_inferno.pdf). What makes afor loopslow and memory hog is growing object within the loop.applydoes hide aforloop, butlapplydoes not, at least explicitly.