I have the following data frame:
我有以下数据框:
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)
typing
打字
table(df)
results in
结果是
period
id calib first valid
1 1 2 0
2 2 0 2
3 0 0 2
4 1 1 1
Is there any way to get the same result using 'dcast' and save it as a new data frame?
有没有办法使用'dcast'获得相同的结果并将其保存为新的数据框?
1 个解决方案
#1
1
Yes, there is a way:
是的,有一种方法:
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
You can also type just dcast(df, id ~ period)
and length
will be chosen by default too. As I can see, you tried to find this out in your another question. Extended solution without dcast
would look like this:
你也可以输入dcast(df,id~句号),默认也会选择长度。我可以看到,你试图在另一个问题中找到它。没有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
#1
1
Yes, there is a way:
是的,有一种方法:
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
You can also type just dcast(df, id ~ period)
and length
will be chosen by default too. As I can see, you tried to find this out in your another question. Extended solution without dcast
would look like this:
你也可以输入dcast(df,id~句号),默认也会选择长度。我可以看到,你试图在另一个问题中找到它。没有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