【问题标题】:Combine list of tibble tables if they have the same columns如果它们具有相同的列,则合并 tibble 表的列表
【发布时间】:2021-09-13 08:13:43
【问题描述】:

我有表格的数据

[[1]] 
   a b c
1  3 4 8 
[[2]] 
   d e f
1  6 7 9 
[[3]] 
   g h i
1  1 4 5 
[[4]] 
   a b c
1  9 5 2 
[[5]] 
   d e f
1  5 8 0

我想把这个结合起来

[[1]]
  a b c
1 3 4 8
2 9 5 2
[[1]]
  d e f
1 6 7 9
2 5 8 0
[[3]]
  g h i
1 1 4 5

也就是说,如果 tibble 表具有相同的列名,我想将它们绑定到列表中。有人可以帮我吗?亲切的问候。

【问题讨论】:

  • 请分享一个可重现的例子
  • 这不是一个可重现的例子吗?
  • list(c(a = 3, b = 4, c = 8), c(d = 6, e = 7, f = 9), c(g = 1, h = 4, i = 5), c(a = 9, b = 5, c = 2), c(d = 5, e = 8, f = 0)) 在您的情况下是可重现的示例。尝试使用dput(data)
  • 没有。我们需要能够在会话中复制/粘贴

标签: r rbind


【解决方案1】:

一个选项可能是:

lapply(split(lst, sapply(lst, function(x) toString(names(x)))), function(y) do.call(rbind, y))

$`a, b, c`
     a b c
[1,] 3 4 8
[2,] 9 5 2

$`d, e, f`
     d e f
[1,] 6 7 9
[2,] 5 8 0

$`g, h, i`
     g h i
[1,] 1 4 5

或者更简洁的选项(由@Ronak Shah 提出):

tapply(lst, sapply(lst, function(x) toString(names(x))), function(x) do.call(rbind, x))

【讨论】:

  • split + lapply 可以替换为tapply,这样会更短一些。 tapply(lst, sapply(lst, function(x) toString(names(x))), function(x) do.call(rbind, x))
  • @Ronak Shah 这很聪明,谢谢你的提示!
【解决方案2】:

这很混乱,但它可能有效

x <- unique(lapply(dummy, function(x) names(x)))
y <- lapply(dummy, function(x) names(x))
z <- match(y, x)
res <- vector(mode = "list", length = 3)
for (i in 1:length(z)) {
  res[[z[i]]] <- rbind(res[[z[i]]], dummy[[i]])
  
}

[[1]]
     a b c
[1,] 3 4 8
[2,] 9 5 2

[[2]]
     d e f
[1,] 6 7 9
[2,] 5 8 0

[[3]]
     g h i
[1,] 1 4 5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-21
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    相关资源
    最近更新 更多