Reputation: 45
I have a list of 10 df in R with 2 columns and I want to add 5 empty columns to each df in the list. The columns have specific names. I imported the df as a list using a for loop.
temp_file = list.files(pattern="*.csv")
my_data <- list()
for (i in seq_along(temp_file)) {
my_data[[i]] <- read.csv(file = temp_file[i])}
So now I have a list of df with 2 columns as below
col_A | col_B |
---|---|
10 | abc |
16 | 78 |
xyz | 295 |
I have a string called new_columns
new_columns <- c("col_C", "col_D", "col_E", "col_xg", "col_W93")
I want to add these 5 empty columns to all the 10 data frames in the list my_data
I tried a for loop and rbind but nothing seems to work
Upvotes: 1
Views: 110
Reputation: 886958
We loop over the list
('my_data'), assign those columns ('new_columns') to blank and return the dataset
my_data <- lapply(my_data, function(x) {x[new_columns] <- ''; x})
Upvotes: 1