【问题标题】:Looping over dataframes in R to change column and row names循环遍历 R 中的数据框以更改列名和行名
【发布时间】:2019-06-29 20:39:09
【问题描述】:

我正在尝试自动化一些代码,处理几个数据框,稍后我将把它们变成 LaTeX 表。我想遍历六个数据框,从中删除相同的列,并将它们的所有列和行重命名为相同的标准名称。

我尝试创建一个基本的 for 循环,但它对数据帧没有任何作用(也没有给出错误)。

row1 <- c(.5,.25,.75)
row2 <- c(.5,.25,.75)
df_1 <- data.frame(rbind(row1,row2))
row3 <- c(.5,.25,.75)
row4 <- c(.5,.25,.75)
df_2 <- data.frame(rbind(row3,row4))
tables <- list(df_1,df_2)
for (i in tables){ 
  rownames(i) <- c("row one","row two")
  colnames(i) <- c("col one","col two","col three")
}
print(df_1)

它打印 df1 没有我试图在循环中分配的行名或列名。如果我在没有 for 循环的情况下手动分配行名,它就可以工作。任何想法为什么?

【问题讨论】:

  • 您正在更改 i 的名称,而不是 df_1 的名称

标签: r dataframe


【解决方案1】:

试试

for (i in seq_along(tables)){ 
  rownames(tables[[i]]) <- c("row one","row two")
  colnames(tables[[i]]) <- c("col one","col two","col three")
  }
print(tables)
#[[1]]
#        col one col two col three
#row one     0.5    0.25      0.75
#row two     0.5    0.25      0.75

#[[2]]
#        col one col two col three
#row one     0.5    0.25      0.75
#row two     0.5    0.25      0.75

【讨论】:

    【解决方案2】:

    或者,您可以使用 lapply 来加快进程并保持列表结构。

    tables <- lapply(list(df_1, df_2), function (df) {
        rownames(df) <- c("row one","row two")
        colnames(df) <- c("col one","col two","col three")
        return (df)
    }
    
    # [[1]]
    #         col one col two col three
    # row one     0.5    0.25      0.75
    # row two     0.5    0.25      0.75
    #
    # [[2]]
    #         col one col two col three
    # row one     0.5    0.25      0.75
    # row two     0.5    0.25      0.75
    

    tables &lt;- lapply(tables, 'dimnames&lt;-', list(c("row one","row two"),c("col one","col two","col three"))),更简洁(感谢@markus)

    【讨论】:

    • 我正要添加此选项:tables &lt;- lapply(tables, 'dimnames&lt;-', list(c("row one","row two"), c("col one","col two","col three"))),您现在可能希望将其包含在您的答案中。它更简洁一些。
    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多