R是否可以使用dcast获取table()的输出?

时间:2012-07-22 09:01:22

标签: r

我有以下数据框:

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'获得相同的结果并将其保存为新的数据框?

1 个答案:

答案 0 :(得分: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。我可以看到,你试图在另一个question找到这个。没有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