是否可以将百分比添加到列联表中(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 0It 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.4285714Thanks 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.429Here 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.429And 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更多推荐
发布评论