是否可以将百分比添加到列联表中(Is it possible to add percentages to a contingency table)

编程入门 行业动态 更新时间:2024-10-27 10:34:57
是否可以将百分比添加到列联表中(Is it possible to add percentages to a contingency table)

我对R中的table()函数有疑问。我想添加一个额外的列来显示table()所做的计数的百分比。 我有这样的数据框:

delta=data.frame(x1=c("x001","x001","x002","x002","x001","x001","x002"),x2=c(1,2,1,1,1,1,1))

当我为这个数据框计算table() ,我得到了这个:

table(delta$x1,delta$x2) 1 2 x001 3 1 x002 3 0

可以在此表中添加百分比,或者R中有任何函数或包来计算如下内容:

1 2 Number Percentage x001 3 1 4 0.5714286 x002 3 0 3 0.4285714

谢谢你的帮助。

I have a question about the table() function in R. I want to add an extra column to show percentages from counts made by table(). I have a data frame like this:

delta=data.frame(x1=c("x001","x001","x002","x002","x001","x001","x002"),x2=c(1,2,1,1,1,1,1))

When I compute table() for this data frame I got this:

table(delta$x1,delta$x2) 1 2 x001 3 1 x002 3 0

It is possible to add percentages in this table or there is any function or package in R to compute something like this:

1 2 Number Percentage x001 3 1 4 0.5714286 x002 3 0 3 0.4285714

Thanks for your help.

最满意答案

这是使用sum()和rowSums()的快速解决方案:

> tbl <- table(delta) > (tbl <- cbind(tbl, rowSums(tbl), rowSums(tbl) / sum(tbl))) 1 2 x001 3 1 4 0.571 x002 3 0 3 0.429

您可以使用colnames()添加列名称; 例如:

> colnames(tbl) <- c("1", "2", "N", "Pct") > tbl 1 2 N Pct x001 3 1 4 0.571 x002 3 0 3 0.429

Here is a quick solution using sum() and rowSums():

> tbl <- table(delta) > (tbl <- cbind(tbl, rowSums(tbl), rowSums(tbl) / sum(tbl))) 1 2 x001 3 1 4 0.571 x002 3 0 3 0.429

And you can add column names with colnames(); e.g.:

> colnames(tbl) <- c("1", "2", "N", "Pct") > tbl 1 2 N Pct x001 3 1 4 0.571 x002 3 0 3 0.429

更多推荐

本文发布于:2023-07-21 09:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1209020.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:百分比   到列联表中   add   table   contingency

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!