Jason Edelkind
Jason Edelkind

Reputation: 83

How to Add a New Row to Multiple dataframes in a List in R

I have a list containing multiple dataframes and I would like to be able to add a new row to each data frame for year

I would like to be able to edit my all my dataframes at the same time, so I started by combining my dataframes into a list

df1 <- data.frame (first_column  = c(0),
               second_column = c(1),
               third_column = c(2))
df2 <- data.frame (first_column  = c(3),
               second_column = c(4),
               third_column = c(5))
df3 <- data.frame (first_column  = c(6),
               second_column = c(7),
               third_column = c(8))
df.list<-list(df1,df2,df3)
names(df.list)<-c("df1","df2","df3")

Next I would like to add a row for year to every dataframe, like this

First Column Second Column Third Column
0 1 2
2000 2000 2000

Though I would like to be able to add different years to different dataframes (2000 to df1, 2001 to df2, 2002 to df3, etc).

I have attempted to create a new row blank for each dataframe using lapply, but this has not been working for me.

newlist <- lapply(df.list, function(x) insertRows(x, 2, new = NA)

I'm also lost on how to add different years to the new rows for different dataframes once I get the blank rows added to the dataframes. Any advice would be greatly appreciated!

Upvotes: 2

Views: 426

Answers (2)

Andre Wildberg
Andre Wildberg

Reputation: 19191

If you have a named list of values to add, with names matching the data frame names

add <- list(df2 = rep(2001, 3), df3 = rep(2002, 3))

add
$df2
[1] 2001 2001 2001

$df3
[1] 2002 2002 2002

using sapply to add each entry to your existing list of data.frames

sapply(names(df_list), function(x) rbind(df_list[[x]], add[[x]]), simplify=F)
$df1
  first_column second_column third_column
1            0             1            2

$df2
  first_column second_column third_column
1            3             4            5
2         2001          2001         2001

$df3
  first_column second_column third_column
1            6             7            8
2         2002          2002         2002

Upvotes: 0

akrun
akrun

Reputation: 887881

Using Map

 Map(rbind, df.list, seq_along(df.list)-1 + 2000)

-output

$df1
  first_column second_column third_column
1            0             1            2
2         2000          2000         2000

$df2
  first_column second_column third_column
1            3             4            5
2         2001          2001         2001

$df3
  first_column second_column third_column
1            6             7            8
2         2002          2002         2002

Upvotes: 4

Related Questions