【问题标题】:Nested List to Single Table (Merge By Column Name?)嵌套列表到单个表(按列名合并?)
【发布时间】:2013-05-16 18:38:30
【问题描述】:

我有一个如下所示的嵌套列表:

dput(head(tempList))
structure(list(Species = c("RandArcBo1", "RandArcBo1", "RandArcBo1", 
"RandArcBo1", "RandArcBo1", "RandArcBo1", "RandArcBo1", "RandArcBo1", 
"RandArcBo1", "RandArcBo1", "RandArcBo1", "RandArcBo1", "RandArcBo1", 
"RandArcBo1", "RandArcBo1", "RandArcBo1"), x = c(132.5, 156.5, 
178.5, 159.5, 166.5, 133.5, 103.5, 162.5, 165.5, 143.5, -163.5, 
178.5, 151.5, 163.5, -120.5, -151.5), y = c(84.567321777, 83.567321777, 
60.567321777, 77.567321777, 56.567321777, 74.567321777, 85.567321777, 
70.567321777, 55.567321777, 74.567321777, 66.567321777, 72.567321777, 
81.567321777, 53.567321777, 85.567321777, 76.567321777), Species = c("RandArcBo2", 
"RandArcBo2", "RandArcBo2", "RandArcBo2", "RandArcBo2", "RandArcBo2", 
"RandArcBo2", "RandArcBo2", "RandArcBo2", "RandArcBo2", "RandArcBo2", 
"RandArcBo2", "RandArcBo2", "RandArcBo2", "RandArcBo2", "RandArcBo2"
), x = c(150.5, 121.5, 169.5, 174.5, 175.5, 153.5, -97.5, 169.5, 
159.5, 166.5, -114.5, -92.5, -176.5, -167.5, 136.5, -133.5), 
    y = c(55.567321777, 76.567321777, 58.567321777, 80.567321777, 
    83.567321777, 82.567321777, 83.567321777, 57.567321777, 75.567321777, 
    55.567321777, 74.567321777, 77.567321777, 68.567321777, 67.567321777, 
    74.567321777, 70.567321777)), .Names = c("Species", "x", 
"y", "Species", "x", "y"))

我想要将这些数据合并到一个包含三列“物种”、“x”和“y”的表格中(每行都标有一个可以重复的物种名称,后跟一个 x,y 坐标) . Cbind 将二阶列表放在彼此相邻的列中,因此我最终得到的列数等于一阶对象数的 3*。 Rbind 将二阶列表放入行中,因此我最终得到的列数等于二阶列表的长度。有什么建议吗?

【问题讨论】:

  • 您可能不想为列表中的项目重复使用名称。 (我什至没有意识到这是可能的。)例如,如果您使用tempList[["x"]],您只会得到具有该名称的第一个项目;甚至没有第二个项目存在的警告。

标签: r nested-lists rbind cbind


【解决方案1】:

这是一个通用的方法:

data.frame(sapply(unique(names(tempList)), 
     function(name) do.call(c, tempList[names(tempList) == name]), simplify=FALSE)
)

【讨论】:

    【解决方案2】:

    splitunlist 对我来说似乎是最直接的方法:

    out <- data.frame(lapply(split(tempList, names(tempList)), 
                             unlist, use.names = FALSE))
    head(out)
    #      Species     x        y
    # 1 RandArcBo1 132.5 84.56732
    # 2 RandArcBo1 156.5 83.56732
    # 3 RandArcBo1 178.5 60.56732
    # 4 RandArcBo1 159.5 77.56732
    # 5 RandArcBo1 166.5 56.56732
    # 6 RandArcBo1 133.5 74.56732
    tail(out)
    #       Species      x        y
    # 27 RandArcBo2 -114.5 74.56732
    # 28 RandArcBo2  -92.5 77.56732
    # 29 RandArcBo2 -176.5 68.56732
    # 30 RandArcBo2 -167.5 67.56732
    # 31 RandArcBo2  136.5 74.56732
    # 32 RandArcBo2 -133.5 70.56732
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 2021-04-10
      • 2022-08-20
      • 2020-05-17
      • 1970-01-01
      相关资源
      最近更新 更多