r - 如何向 R 列表中的多个数据帧添加新行

标签 r

我有一个包含多个数据框的列表,我希望能够向每年的每个数据框添加一个新行

我希望能够同时编辑所有数据帧,因此我首先将数据帧合并到一个列表中

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")

接下来我想向每个数据帧添加一行代表年份,如下所示

<表类=“s-表”> <标题> 第一列 第二列 第三列 <正文> 0 1 2 2000 2000 2000

虽然我希望能够将不同的年份添加到不同的数据帧(2000年到df1、2001年到df2、2002年到df3等)。

我尝试使用 lapply 为每个数据帧创建一个新的行空白,但这对我不起作用。

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

一旦将空白行添加到数据帧中,我也会迷失如何向不同数据帧的新行添加不同的年份。任何建议将不胜感激!

最佳答案

使用 map

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

-输出

$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

关于r - 如何向 R 列表中的多个数据帧添加新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75537372/

相关文章:

从 R 中的数据表中删除一行

r - 调用rmarkdown::render时接收器已满

r - 如何使用函数 ggplot() 和 plot_ly 增加 R 中轴标签和轴标题之间的空间?

r - 在r中以相同的pdf或png输出textplot和qplot

r - 多个 ggplots 导致图例问题

r - 使用 nplot/rCharts 制作 NVD3 scatterChart 时访问点的形状属性

R ggplot2 : how do I plot an implicit function (contour line at just one level)?

r - 如何在r中创建多折线图

r - 'arg' 必须为 NULL 或字符向量

R dbReadTable 返回没有这样的表错误