如何在表列表中使用bind_rows?

时间:2018-04-18 21:08:53

标签: r

假设我有三个表格如下:

table1 <- structure(list(Pos = 1:6, A = c(16.8508287292818, 0, 0.552486187845304, 
0, 1.10497237569061, 1.38121546961326), C = c(1.93370165745856, 
0.276243093922652, 0.828729281767956, 0.276243093922652, 0, 0.552486187845304
), G = c(1.10497237569061, 2.48618784530387, 0.276243093922652, 
0.828729281767956, 0.276243093922652, 0), T = c(0.828729281767956, 
0, 0.828729281767956, 1.10497237569061, 0, 0)), .Names = c("Pos", 
"A", "C", "G", "T"), row.names = c(NA, 6L), class = "data.frame")

table2<- structure(list(Pos = 1:6, A = c(4.15584415584416, 1.03896103896104, 
0.779220779220779, 0.692640692640693, 2.25108225108225, 2.94372294372294
), C = c(1.12554112554113, 0.173160173160173, 0.173160173160173, 
0.519480519480519, 0.173160173160173, 0.173160173160173), G = c(1.03896103896104, 
0.346320346320346, 0.0865800865800866, 0.432900432900433, 0.519480519480519, 
0.0865800865800866), T = c(2.77056277056277, 0.606060606060606, 
0.25974025974026, 0.692640692640693, 0.346320346320346, 0.25974025974026
)), .Names = c("Pos", "A", "C", "G", "T"), row.names = c(NA, 
6L), class = "data.frame")
table3 <- structure(list(Pos = 1:6, A = c(10.3492063492063, 0.317460317460317, 
0.349206349206349, 0.920634920634921, 1.96825396825397, 1.23809523809524
), C = c(0.825396825396825, 0.126984126984127, 0.349206349206349, 
0.317460317460317, 0.19047619047619, 0.253968253968254), G = c(0.761904761904762, 
0.952380952380952, 0.285714285714286, 0.412698412698413, 0.126984126984127, 
0.19047619047619), T = c(1.07936507936508, 0.412698412698413, 
0.476190476190476, 0.253968253968254, 0.19047619047619, 0.253968253968254
)), .Names = c("Pos", "A", "C", "G", "T"), row.names = c(NA, 
6L), class = "data.frame")

我现在已将表名保存为files.table

files.table <- paste0("table", seq(1:3))

我的问题是我无法运行此bind_rows函数来使用files.table绑定table1,table2和table3,而不是列出所有三个表。这是我得到的错误:Error in bind_rows_(x, .id) : Argument 1 must have names

这是我尝试过的代码:

bind.table <- bind_rows(files.table, .id = "table") %>%
      gather(Base, Percent, -Pos, -table)

1 个答案:

答案 0 :(得分:2)

bind_rows的{​​{1}}参数设置变量的名称,该变量包含每行来自的列表项的名称,而不是这些名称本身。您可以通过命名列表中的项目来设置表名称。然后,bind_rows将获取这些名称并将其放入具有您指定名称的列中:

table_list <- list(table1, table2, table3)
names(table_list) <- paste0("table", seq(1:3))
bind.table <- bind_rows(table_list, .id = 'id')

来自?bind_rows

  

每个参数可以是数据框,也可以是数据列表   框架或数据框列表

将数据帧放入bind_rows的最简单方法是将它们组合成一个列表,然后只传递数据帧列表。正如@joran建议的那样,最简单的方法是加载或在lapply函数中生成它们,这将自动输出可以进入bind_rows的列表。