hanzgs
hanzgs

Reputation: 1616

How to rbind multiple data frames individually in R?

There is a data frame (df) and a list of data frames(df1,df2..), I want to rbind df with each df's in list and store in a new list.

50 data frames list

mylist # List of 50 elements

Another base data frame

single_data

I created an empty list

my_dfs = list()

I want to rbind single_data to every data frame in the list

for (i in 1:length(mylist)){
  my_dfs[[i]] <- rbind(single_data, mylist$`i`) 
}

But rbind not happening, single_data has 5000 rows and mylist data frames has 5000 rows each, but my_dfs[[i]] having only 5000 rows. If I do individually instead of loop it is working.

my_dfs1 <- rbind(single_data, mylist$`1`) 
my_dfs2 <- rbind(single_data, mylist$`2`) …

I except to work on loop.

Upvotes: 1

Views: 457

Answers (1)

akrun
akrun

Reputation: 887048

We can use lapply to loop over the list and rbind the 'single_data' with each of the list elements

mylistnew <- lapply(mylist, function(x) rbind(single_data, x))

If we use the for loop, use the [[ instead of $. Also, it is better to have seq_along instead of 1:length

my_dfs <- vector('list', length(mylist))

for (i in seq_along(mylist)){
  my_dfs[[i]] <- rbind(single_data, mylist[[i]]) 
 }

Upvotes: 3

Related Questions