Unclass x tabs on data frame

r

Solution

I'm sure there's a way to do this with `xtabs` but I tend to use `dcast` instead:

library(reshape2)
dcast(dat,LOCATION+COLOR~STATE,
      fun.aggregate = length,value.var = "STATE",drop = FALSE)
  LOCATION COLOR fresh rotten
1        A green     1      0
2        A   red     0      1
3        B green     2      0
4        B   red     0      0
5        C green     0      1
6        C   red     1      0

Updated to include missing variable combinations as indicated in desired output.

Problem

I have the following data frame in R ``` LOCATION COLOR STATE 1 A green fresh 2 A red rotten 3 B green fresh 4 B green fresh 5 C red fresh 6 C green rotten ``` The above data frame can be created in R by using the following script ``` dat <- read.table(text = "LOCATION COLOR STATE 1 A green fresh 2 A red rotten 3 B green fresh 4 B green fresh 5 C red fresh 6 C green rotten",header = TRUE,sep = "",row.names = 1) ``` I am trying to rearrange my data frame to get the following output ``` LOCATION COLOR ROTTEN FRESH 1 A red 1 0 2 A green 0 1 3 B red 0 0 4 B green 0 2 5 C red 0 1 6 C greed 1 0 ``` I am trying to do this using the following code ``` dat <- as.data.frame(unclass(xtabs(~ LOCATION + COLOR + STATE,dat))) ``` which gives me ``` green.fresh red.fresh green.rotten red.rotten 1 A 1 0 0 1 2 B 2 0 0 0 3 C 0 1 1 0 ``` As you can see, I am very close to the desired format but I am not sure how to make my current output match my desired output. Any ideas or hints would be appreciated.

Original source

Related problems