我有一个关于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谢谢你的帮助。
发布于 2013-04-08 03:22:18
下面是一个使用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发布于 2013-04-08 03:32:33
您可以使用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编辑
当然你可以这样做
rowSums(prop.table(tbl))
x001 x002
0.5714286 0.4285714 但我的回答是,R中有一些内置函数可以完成table函数。
发布于 2013-04-08 03:14:16
计算并不是很复杂。
可能会让您犯错的是,该表不能直接转换为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.86https://stackoverflow.com/questions/15866488
复制相似问题