开发者

converting an ftable to a matrix

Take for example the following ftable

height <- c(rep('short', 7), rep('tall', 3))
girth <- c(rep('narrow', 4), rep('wide', 6))
measurement <- rnorm(10)
foo <- data.frame(height=height, girth=girth, measurement=measurement)
ftable.result <- ftable(foo$height, foo$girth)

I'd like to convert 开发者_运维知识库the above ftable.result into a matrix with row names and column names. Is there an efficient way of doing this? as.matrix() doesn't exactly work, since it won't attach the row names and column names for you.

You could do the following

ftable.matrix <- ftable.result
class(ftable.matrix) <- 'matrix'

rownames(ftable.matrix) <- unlist(attr(ftable.result, 'row.vars'))
colnames(ftable.matrix) <- unlist(attr(ftable.result, 'col.vars'))

However, it seems a bit heavy-handed. Is there a more efficient way of doing this?


It turns out that @Shane had originally posted (but quickly deleted) what is a correct answer with more recent versions of R.

Somewhere along the way, an as.matrix method was added for ftable (I haven't found it in the NEWS files I read through though.

The as.matrix method for ftable lets you deal fairly nicely with "nested" frequency tables (which is what ftable creates quite nicely). Consider the following:

temp <- read.ftable(textConnection("breathless yes no
coughed yes no
age
20-24  9  7  95 1841
25-29 23  9 108 1654
30-34 54 19 177 1863"))

class(temp)
# [1] "ftable"

The head(as.table(...), Inf) trick doesn't work with such ftables because as.table would convert the result into a multi-dimensional array.

head(as.table(temp), Inf)
#  [1]    9   23   54   95  108  177    7    9   19 1841 1654 1863

For the same reason, the second suggestion also doesn't work:

t <- as.table(temp)
class(t) <- "matrix"
# Error in class(t) <- "matrix" : 
#   invalid to set the class to matrix unless the dimension attribute is of length 2 (was 3)

However, with more recent versions of R, simply using as.matrix would be fine:

as.matrix(temp)
#        breathless_coughed
# age     yes_yes yes_no no_yes no_no
#   20-24       9      7     95  1841
#   25-29      23      9    108  1654
#   30-34      54     19    177  1863

class(.Last.value)
# [1] "matrix"

If you prefer a data.frame to a matrix, check out table2df from my "mrdwabmisc" package on GitHub.


I found 2 solutions on R-Help:

head(as.table(ftable.result), Inf)

Or

t <- as.table(ftable.result)
class(t) <- "matrix"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜