[R] Odp: xtabs - missing combination

Petr PIKAL petr.pikal at precheza.cz
Mon Dec 14 08:35:18 CET 2009


Hi

I am not sure if it solves your problem

tab1<-xtabs(value ~ r07 + r08, df1)
tab1[xtabs( ~ r07 + r08, df1)==0]<-NA
tab1
   r08
r07  A  B  C  D
  A  1  2     4
  B  5  6  7  8
  C  9 10 11 12
  D 13  0 15 16
>

however this is slightly different from tapply output. As I understand 
help page if you put value at the left hand side you get result summed for 
all levels. Combination AC does not exist however A and C levels are 
present so the result tells you correctly that the sum of AC combination 
is zero.

Regards
Petr




r-help-bounces at r-project.org napsal dne 13.12.2009 01:21:48:

> Dear list,
> 
> I am trying to make a contingency table with xtabs but I am getting
> a 0 where I expect a 'NA'. Here is a simple example:
> 
> options(stringsAsFactors = FALSE)
> rn <- LETTERS[1:4]
> df1 <- data.frame(r07 = rep(rn, each=4),
>                    r08 = rep(rn, 4), value = 1:16)
> xtabs(value ~ r07 + r08, df1)
> 
> # Delete the combination [A, C]
> df1 <- df1[-3,]
> 
> # Set 'value' for this combination to 0
> df1[13, 3] <- 0
> 
> # This is the output I want
> tapply(df1[, "value"], df1[, c("r07", "r08")], c)
> 
> # but using 'xtabs' I get a 0 for [A, C]
> xtabs(value ~ r07 + r08, df1)
> 
> Hmm, what have I missed...
> 
> Thanks for any help!
> 
> Best,
> Patrick
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list