[R] creating objects of class "xtabs" "table" in R
Deepayan Sarkar
deepayan.sarkar at gmail.com
Fri Oct 5 22:09:42 CEST 2007
On 10/5/07, born.to.b.wyld at gmail.com <born.to.b.wyld at gmail.com> wrote:
> I have an application that would generate a cross-tabulation in array
> format in R. In particular, my application would give me a result
> similar to that of :
>
> array(5,c(2,2,2,2,2))
>
> The above could be seen as a cross-tabulation of 5 variables with 2
> levels each (could be 0 and 1). In this case, the data were such that
> each cell has exactly 5 observations. I
>
> Now, I want the output to look like the output of 'xtabs' utility, so
> that I can use this output inside 'loglm(MASS)'. In particular, I want
> to add (variable) names to each dimension and indicate the levels that
> correspond to each cell. The output from 'xtabs' for a data set of
> this kind would look like:
Simplifying your example:
> foo <- array(5,c(2,2), dimnames = list(xx = c("x=0", "x=1"), yy = c("A", "B")))
> foo
yy
xx A B
x=0 5 5
x=1 5 5
You can also do this in two steps:
foo <- array(5,c(2,2))
dimnames(foo) <- list(xx = c("x=0", "x=1"), yy = c("A", "B"))
[...]
> Now, I do not generate my output using the 'xtabs' utility. In fact,
> my simulations would generate the cross-table directly and not the
> dataset.
>
> Can anyone help? R examples have some reference to the 'dimnames'
> attribute, but I am not exactly sure.
> Also, is there an R function that could do the exact opposite of
> 'xtabs', that is, may be generate a data frame given its cross-table?
Sort of (there is only one column for each combination, giving `frequencies'):
> as.data.frame.table(foo)
xx yy Freq
1 x=0 A 5
2 x=1 A 5
3 x=0 B 5
4 x=1 B 5
If foo has class "table", then as.data.frame(foo) would also work.
-Deepayan
More information about the R-help
mailing list