R 是否可以将百分比添加到列联表中

R 是否可以将百分比添加到列联表中,r,R,我对R中的table()函数有一个问题。我想添加一个额外的列来显示table()计数的百分比。我有这样一个数据框: delta=data.frame(x1=c("x001","x001","x002","x002","x001","x001","x002"),x2=c(1,2,1,1,1,1,1)) 1 2 Number Percentage x001 3 1 4 0.5714286 x002 3 0 3 0.4285714 当我为这个数据

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

delta=data.frame(x1=c("x001","x001","x002","x002","x001","x001","x002"),x2=c(1,2,1,1,1,1,1))
       1 2  Number Percentage
  x001 3 1    4     0.5714286
  x002 3 0    3     0.4285714
当我为这个数据帧计算
table()
时,我得到了以下结果:

table(delta$x1,delta$x2)

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

delta=data.frame(x1=c("x001","x001","x002","x002","x001","x001","x002"),x2=c(1,2,1,1,1,1,1))
       1 2  Number Percentage
  x001 3 1    4     0.5714286
  x002 3 0    3     0.4285714

谢谢你的帮助。

计算不是很复杂。
可能让您感到困惑的是,该表没有直接转换为data.frame。至少不是你想要的那样。这里是一个分解,一步一步

# this is the basic table, we want it as a data.frame
delCounts <- table(delta)

# you need to convert the table to a matrix, before converting to a data.frame
results <- data.frame(matrix(delCounts, nrow=nrow(delCounts)))

# you may want to preserve the names.  Have a look: 
dimnames(delCounts)  # first are the column names, then row names

colnames(results) <- dimnames(delCounts)[[1]]
rownames(results) <- dimnames(delCounts)[[2]]

# Now sum up and take percentages
# we can use vectorized arithmetic operations for the percentage
results$Number <- rowSums(results)
results$Percentage <- results$Number / sum(results$Number)

# we might want to round instead
results$Percentage <- round(results$Number / sum(results$Number)*100, 2)

results
#   x001 x002 Number Percentage
# 1    3    1      4      57.14
# 2    3    0      3      42.86
#这是基本表,我们希望它作为data.frame

delCounts这里有一个使用
sum()
rowSums()
的快速解决方案:


您可以使用
prop.table
addmargins

tbl <- table(delta$x1,delta$x2)

prop.table(tbl)

# 1         2
# x001 0.4285714 0.1428571 
# x002 0.4285714 0.0000000

addmargins(tbl)

# 1 2 Sum
# x001 3 1   4
# x002 3 0   3
# Sum  6 1   7

但我的答案是,R中有一些内置函数,可以完成
表的功能。

我不知道prop.table如何单独解决OP的问题。你仍然需要对结果求和,不是吗?@RicardoSaporta你可以添加
rowSums
。问题是关于R中任何计算
之类的东西的函数。。。我希望编辑后我的答案是清楚的。我跟随你,你可以总结道具表。我只是觉得
prop.table
addmargins
对于这个答案不太合适。也就是说,您不能执行
cbind(addmargins(tbl)、行和(prop.table(tbl))
@RicardoSaporta不可以尝试此操作,例如
cbind(addmargins(tbl,2)、行和(prop.table(tbl))
。但这并不重要,正如我之前所说,我的答案主要是确保OP有这样的功能存在。(感谢您的严格要求)还可以添加一些带有
cbind的列名(tbl,Sums=rowSums(tbl),Pct=
。。。
rowSums(prop.table(tbl)) 
     x001      x002 
0.5714286 0.4285714