新的 R 用户拆包数据

New R user unstacking data

我的数据每个 memberID 有多行。我在下面对其进行了模拟(请参阅#this is what I have)。我需要将其转换为每个 memberID 一行的形状,从而创建多列。我也在下面模拟了所需的输出(参见#this is what I want)。我正在寻找在 R 中进行这种转换的最简单方法。我是一个全新的 R 和 RStudio 用户,几乎没有编码背景。非常感谢代码方面的帮助。

#this is what I have

ID <- c(1,1,2,3,3,3)  
Date <- as.Date (c("2015/01/01","2016/01/03", "2011/03/01", "2015/01/09", "2017/12/11","2016/09/09" )) 
Score <- c(5,15,2,6,12,18)  
df <- data.frame(ID, Date, Score)
df

#this is what i want

ID2 <- c(1,2,3)  
Date1 <- as.Date (c("2015/01/01","2011/03/01","2015/01/09"))
Date2 <- as.Date (c("2016/01/03", NA, "2017/12/11"))
Date3 <- as.Date (c(NA, NA,"2016/09/09"))
Score1 <- c(5,2,6)
Score2 <- c(15,NA,12) 
Score3 <- c("NA","NA",18) 
df2 <- data.frame (ID2, Date1, Date2, Date3, Score1, Score2, Score3)
df2

我们可以使用 data.table 中的 dcast,它可以包含多个 value.var

library(data.table)
dcast(setDT(df), ID~rowid(ID), value.var = c("Date", "Score"), sep="")
#   ID      Date1      Date2      Date3 Score1 Score2 Score3
#1:  1 2015-01-01 2016-01-03       <NA>      5     15     NA
#2:  2 2011-03-01       <NA>       <NA>      2     NA     NA
#3:  3 2015-01-09 2017-12-11 2016-09-09      6     12     18