I want to create multiple columns using the apply function. The idea is to use the apply to create new columns using paste0 to define the name. Follows an example:
Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)
Number <- 1:4
df <- data.frame(Name, Age)
creating_columns <- function(number){
df[paste0("new_",number)] <- number
return(df)
}
lapply(Number,creating_columns)
The code doesn't work. I have just a list of four different data frames, and in each one, I have a new column but I wanted the final data with all new columns. I can use for to create this, but my real data frame is too big so it takes too long. Follows the code that works:
for (number in Number){
df[paste0("new_",number)] <- number
}
I want the following:
Name Age new_1 new_2 new_3 new_4
1 Jon 23 1 2 3 4
2 Bill 41 1 2 3 4
3 Maria 32 1 2 3 4
4 Ben 58 1 2 3 4
5 Tina 26 1 2 3 4