将 ftable 转换为矩阵
以下面的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)
我想将上面的ftable.result转换为具有行名称和列名称的矩阵。有没有有效的方法来做到这一点? as.matrix()
并不完全有效,因为它不会为您附加行名称和列名称。
您可以执行以下操作
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'))
,但是,这似乎有点严厉。有没有更有效的方法来做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实证明,@Shane 最初发布了(但很快就删除了)最新版本 R 的正确答案。
在此过程中的某个地方,出现了一个
as.matrix
方法已为ftable
添加(尽管我在阅读的新闻文件中没有找到它。ftable
的as.matrix
方法可以让您很好地处理“嵌套”频率表(这是ftable
很好地创建的)。考虑以下内容:head(as.table(...), Inf)
技巧不适用于此类ftables
,因为as.table
会将结果转换为多维数组出于同样的原因,第二个建议也不起作用。工作:
但是,对于更新版本的 R,只需使用
as.matrix
就可以了:如果您更喜欢
data.frame
而不是matrix
>,从我的 GitHub 上的 "mrdwabmisc" 包中查看table2df
。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 forftable
(I haven't found it in the NEWS files I read through though.The
as.matrix
method forftable
lets you deal fairly nicely with "nested" frequency tables (which is whatftable
creates quite nicely). Consider the following:The
head(as.table(...), Inf)
trick doesn't work with suchftables
becauseas.table
would convert the result into a multi-dimensional array.For the same reason, the second suggestion also doesn't work:
However, with more recent versions of R, simply using
as.matrix
would be fine:If you prefer a
data.frame
to amatrix
, check outtable2df
from my "mrdwabmisc" package on GitHub.我找到了2个解决方案在 R-Help 上:
或者
I found 2 solutions on R-Help:
Or