【问题标题】:How can I gather data in a column depending on another value from another column (Difficult question)如何根据另一列的另一个值在一列中收集数据(难题)
【发布时间】:2022-11-24 02:12:29
【问题描述】:

因为一张表值一千字,所以我想做的是:

Column A Column B Column C Column D
AMY 1.5 x1 y1
STR 2 x2 y2
AMY 4.5 x2 y3
STR 3 x3 y4

我想根据列 A 的值将列 B 中的所有数据重新组合到列中。 A 列的每个值形成一个列名称。这个,在一个新的数据框中。

AMY STR
1.5 2
4.5 3

非常感谢 !

我尝试使用 gather() 和 unite() 实现它,但它没有给我预期的结果。

【问题讨论】:

    标签: r rstudio columnsorting


    【解决方案1】:

    如果数据集对 ColumnA 值具有相同数量的观察值,则在 base R 中选择列和 unstack

    unstack(df1[1:2], `Column B`~ `Column A`)
      AMY STR
    1 1.5   2
    2 4.5   3
    

    数据

    df1 <- structure(list(`Column A` = c("AMY", "STR", "AMY", "STR"), 
    `Column B` = c(1.5, 
    2, 4.5, 3), `Column C` = c("x1", "x2", "x2", "x3"), `Column D` = c("y1", 
    "y2", "y3", "y4")), class = "data.frame", 
    row.names = c(NA, -4L
    ))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 2022-01-26
      • 2019-07-08
      • 2021-03-16
      相关资源
      最近更新 更多