我正在和加州大学洛杉矶分校的样本数据集合作
> read <- read.table("http://www.ats.ucla.edu/stat/mult_pkg/faq/general/sample.csv",
header=TRUE, sep=",", quote="\"")
> head(read)
female read write math hon femalexmath
1 0 57 52 41 0 0
2 1 68 59 53 0 53
3 0 44 33 54 0 0
4 0 63 44 47 0 0
我想用crosstab
变量hon
和female
所需的结果类似于这个stata
输出:
| female
hon | male female | Total
-----------+----------------------+----------
0 | 74 77 | 151
1 | 17 32 | 49
-----------+----------------------+----------
Total | 91 109 | 200
使用R
,我尝试使用xtabs
> xtabs(female~hon, data = read)
hon
0 1
77 32
和reshape2
> library(reshape2)
> melt <- melt(read, id="female")
> dcast(melt, variable ~ female, sum, subset = .(variable == "hon"))
hon
0 1
77 32
和table
> table(read$hon, read$female)
0 1
0 74 77
1 17 32
但这只是预期结果的一部分。
我希望包含non-female
(=male
)值,并计算总数,并适当地分配名称。
在R
中,我缺少一个简单的函数吗?
我看过这个帖子模拟R中Stata的制表命令,但是由于这个问题中的代码没有包含库gmodels
for CrossTable
,所以我无法应用它。输出看起来也不一样。
发布于 2015-03-31 15:19:16
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 |
-------------|-----------|-----------|-----------|
指定所有这些参数都很繁琐,因此,如果您经常使用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)))
}
就这样说吧:
with(read, tab(hon, gender))
https://stackoverflow.com/questions/29371814
复制相似问题