2

Is it possible to add a vector as a column to a tables object created by tabular {tables}? For example, the following table

df = data.frame(group = factor(rep(c('A', 'B'), each=9)), condition=factor(rep(c('low', 'medium', 'high'), 6)), x=rnorm(18))
library('tables')
tabular(x * group ~ condition * mean, df)

       high      low      medium
   A   1.0818    0.7925   0.3255
   B   0.1312   -0.5851   0.3376

Now say I want to add a new column with some value computed from the data that made up the whole row, i.e. an F statistic:

library('plyr')
fstatistic = ddply(df, .(group), function(df.sub) summary.lm(aov(x ~ condition, df.sub))$fstatistic['value'])

  group     value
1     A 5.7021984
2     B 0.6701893

I want to add this as a column "F" to the far right of this table. How can I do that? To be explicit, the result should be:

       high      low      medium   F
   A   1.0818    0.7925   0.3255   5.7021984
   B   0.1312   -0.5851   0.3376   0.6701893

Or even better: F is calculated from the row in the table. Is there any way to specify a tabular formula in a way that makes this makes this table in one go?

Jonas Lindeløv
  • 5,442
  • 6
  • 31
  • 54

1 Answers1

1

I don't think there's a nice way to define a function for tabular. Functions in tabular operate on individual data vectors, not whole tables, so your lm.fit won't work. Instead just do

tblr <- tabular(x * group ~ condition * mean, df)
tblr <- as.matrix(tblr, rowLabels=FALSE, colLabels=FALSE)
f.statistic <- ddply(df, .(group), function(df.sub) summary.lm(
      aov(x ~ condition, df.sub))$fstatistic['value'])
cbind(tblr, f.statistic)
  • Thanks, this goes a lot of the way. However, labels for rows and columns disappear with this solution. That's manageable in the case of this minimal simple two-factor table but in my actual code I have a larger table (two factors for rows and two factors for columns). Is there a way to preserve these labels? – Jonas Lindeløv Nov 07 '14 at 14:09
  • yes, copy the row and column names over yourself using e.g. `rownames(tblr) <- whatever you want`. –  Nov 07 '14 at 19:02