Reshape/Transpose 在 R studio 中将行复制到列

Reshape/Transpose duplicated rows to column in R studio

我有这样的数据:

ID Name Adress Score Requirement Status
1 John CA 1 Internet OK
1 John CA 1 TV Not OK
1 John CA 1 Household OK
2 Ann LA 3 Internet Not OK
2 Ann LA 3 TV Follow up
... ... ... ... ... ...

每个“客户”的ID都是唯一的,从第1-3行开始,ID、姓名、地址和分数都是相同的。每个客户有 3 个要求,我想将这 3 个要求转换为状态为值的列,以便删除重复项。如下:

ID Name Adress Score Internet TV Household
1 John CA 1 OK Not OK OK
2 Ann LA 3 Not OK Follow up OK
... ... ... ... ... ... ...

我尝试在 R studio 中搜索 reshape 和 dcast 之前的案例,但没有找到与我的相似的案例。 有人能帮我吗?非常感谢!

您可以使用 tidyr 包中的pivot_wider

library(dplyr)
library(tidyr)

# your data
df <- tribble(
  ~ID, ~Name, ~Adress, ~Score, ~Requirement, ~Status,
  1, "John", "CA", 1, "Internet", "OK", 
  1, "John", "CA", 1, "TV", "Not OK", 
  1, "John", "CA", 1, "Household", "OK", 
  2, "Ann", "LA", 3, "Internet", "Not OK", 
  2, "Ann", "LA", 3, "TV", "Follow up")


df <- df %>% 
  pivot_wider(names_from = Requirement, values_from = Status)