[R] calculate adjacent log odds for a table

Michael Friendly friendly at yorku.ca
Wed Jul 22 16:33:29 CEST 2015


On 7/21/2015 11:14 AM, Michael Friendly wrote:
> More generally, for an I x J x K table, where the last factor is the
> response, my desired result
> is a data frame of IJ(K-1) rows, with adjacent log odds in a 'logodds'
> column, and ideally, I'd like
> to have a general function to do this.
>
> Note that if T is the 10 x 3 matrix of frequencies shown by ftable(),
> the calculation is essentially
>
> log(T) %*% matrix(c(1, -1, 0,
>                      0,  1, -1))
> followed by reshaping and labeling.

No one answered, but as I often find, writing it out as a MWE was 
helpful.  Here is a simpler approach for my sample case, that should be
easier to generalize

# reshape to matrix
T <- matrix(mice.tab, nrow=prod(dim(mice.tab)[1:2]), ncol=dim(mice.tab)[3])
colnames(T) <- dimnames(mice.tab)[[3]]
rn <- expand.grid(litter=factor(7:11), treatment=c("A","B"))
rownames(T) <- apply(rn, 1, paste, collapse=":")
T
# calculate log odds as contrasts
C <- matrix(c(1, -1, 0,
               0,  1, -1), nrow=3)
lodds <- log(T) %*% C
colnames(lodds) <- c("0:1", "1:2+")
lodds

 > lodds
             0:1       1:2+
7:A   1.6625477  0.7884574
8:A   1.2527630  0.3364722
9:A   0.6061358  0.1823216
10:A  0.1431008 -0.1431008
11:A -1.0986123 -0.3483067
7:B   1.3730491  0.9985288
8:B   1.2272297  0.7537718
9:B   0.7156200  0.7884574
10:B  0.5725192  0.2006707
11:B -1.0986123  0.6286087
 >

# make a data frame
DF2 <- data.frame(expand.grid(litter=factor(7:11), treatment=c("A","B"), 
deaths=c("0:1", "1:2+")),
	logodds=c(lodds))



More information about the R-help mailing list