【问题标题】:Combine rows into one row in R [duplicate]在R中将行合并为一行[重复]
【发布时间】:2019-12-19 21:16:53
【问题描述】:

我正在尝试以特定方式合并数据框中的行。我不知道该怎么做,但下面我有一个示例输入和所需的输出。

解释一下,假设我们有 2 名员工,id = 1 和 2 标识。这些员工中的每一个都会收到主管的评估,主管可能是同一个人(员工 2 有 2 项来自 John 的评估)。最后,每位主管根据 2 个问题对每位员工进行评分,评分范围为 0 到 4。

x = data.frame(
  employee_id = c(1, 1, 2, 2),
  supervisor = c("John.1", "George.1", "John.1", "John.2"),
  q1 = c(4, 1, 0, 4),
  q2 = c(1, 2, 1, 3)
)

我想为每个员工将其合并为一行,以便输出如下所示:

y = data.frame(
  employee_id = c(1, 2),
  John.1_q1 = c(4,0),
  John.1_q2 = c(1,1),
  George.1_q1 = c(1, NA),
  George.1_q2 = c(2, NA),
  John.2_q1 = c(NA, 4),
  John.2_q2 = c(NA,3)
)

我猜这可以使用 reshape 包来完成,但我无法让它工作。

【问题讨论】:

    标签: r reshape reshape2


    【解决方案1】:

    我们可以使用pivot_wider

    library(tidyr)
    library(dplyr)
    library(stringr)
    pivot_wider(x, names_from = supervisor, values_from = c(q1, q2)) %>%  
         rename_at(-1, ~ str_replace(., "(.*)_(.*)", "\\2_\\1"))
    

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2015-09-05
      • 2013-12-04
      • 1970-01-01
      • 2016-02-11
      • 2020-09-28
      相关资源
      最近更新 更多