1

我有以下数据框:

id<-c(1,2,3,4,1,1,2,3,4,4,2,2)
period<-c("first","calib","valid","valid","calib","first","valid","valid","calib","first","calib","valid")
df<-data.frame(id,period)

打字

table(df) 

结果是

period
id  calib first valid
1     1     2     0
2     2     0     2
3     0     0     2
4     1     1     1

有没有办法使用“dcast”获得相同的结果并将其保存为新的数据框?

4

1 回答 1

1

是的,有一种方法:

library(reshape2)
dcast(df, id ~ period, length)
Using period as value column: use value.var to override.
  id calib first valid
1  1     1     2     0
2  2     2     0     2
3  3     0     0     2
4  4     1     1     1

您也可以只输入dcast(df, id ~ period)length默认情况下也会被选中。如我所见,您试图在另一个问题中找到这一点。没有的扩展解决方案dcast如下所示:

df <- data.frame(unclass(table(df)))
df$ID <- rownames(df)
df
  calib first valid ID
1     1     2     0  1
2     2     0     2  2
3     0     0     2  3
4     1     1     1  4
于 2012-07-22T09:22:07.870 回答