与R中的Stata类似的交叉表
我在加州大学洛杉矶分校工作 使用与R中的Stata类似的交叉表,r,crosstab,reshape2,R,Crosstab,Reshape2,我在加州大学洛杉矶分校工作 使用R,我尝试使用xtabs > xtabs(female~hon, data = read) hon 0 1 77 32 和重塑2 > library(reshape2) > melt <- melt(read, id="female") > dcast(melt, variable ~ female, sum, subset = .(variable == "hon")) hon 0 1 77 32 但这只是预期结
R
,我尝试使用xtabs
> xtabs(female~hon, data = read)
hon
0 1
77 32
和重塑2
> library(reshape2)
> melt <- melt(read, id="female")
> dcast(melt, variable ~ female, sum, subset = .(variable == "hon"))
hon
0 1
77 32
但这只是预期结果的一部分
我想包括非女性
(=男性
)值,计算总数,并适当地分配名称
我是否缺少R
中的一个简单函数
我看过这篇文章,但是由于这个问题中的代码没有包含交叉表的库gmodels
,所以我无法应用它。输出看起来也不一样
library(gmodels)
read$gender <- ifelse(read$female==1, "Female", "Male")
with(read, CrossTable(hon, gender, prop.c=FALSE, prop.r = FALSE, prop.t = FALSE, prop.chisq = FALSE))
指定所有这些参数都很繁琐,因此如果您经常使用CrossTable()
函数,您可以编写一个包装函数:
tab <- function(x, y) {
argx <- deparse(substitute(x))
argy <- deparse(substitute(y))
return(CrossTable(x, y, prop.c=FALSE, prop.r = FALSE, prop.t = FALSE, prop.chisq = FALSE, dnn = c(argx, argy)))
}
addmargins(table(read$hon,read$female))
?我看到这篇文章的可能副本,但这看起来与我在文章中提到的stata输出不同。大卫评论的补充:addmargins(table(read$hon,read$female,dnn=c(“hon”,“female”))
thx@davidernburg,这就是我要找的。我在链接的帖子中做了一个编辑,它引用了包gmodels
。我的帖子似乎是重复的
> table(read$hon, read$female)
0 1
0 74 77
1 17 32
library(gmodels)
read$gender <- ifelse(read$female==1, "Female", "Male")
with(read, CrossTable(hon, gender, prop.c=FALSE, prop.r = FALSE, prop.t = FALSE, prop.chisq = FALSE))
Cell Contents
|-------------------------|
| N |
|-------------------------|
Total Observations in Table: 200
| gender
hon | Female | Male | Row Total |
-------------|-----------|-----------|-----------|
0 | 77 | 74 | 151 |
-------------|-----------|-----------|-----------|
1 | 32 | 17 | 49 |
-------------|-----------|-----------|-----------|
Column Total | 109 | 91 | 200 |
-------------|-----------|-----------|-----------|
tab <- function(x, y) {
argx <- deparse(substitute(x))
argy <- deparse(substitute(y))
return(CrossTable(x, y, prop.c=FALSE, prop.r = FALSE, prop.t = FALSE, prop.chisq = FALSE, dnn = c(argx, argy)))
}
with(read, tab(hon, gender))