1

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?

AliCivil
  • 2,003
  • 6
  • 28
  • 43

1 Answers1

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:

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
Community
  • 1
  • 1
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102