【发布时间】:2015-03-31 15:00:12
【问题描述】:
我在加州大学洛杉矶分校工作sample data set
> 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 中的简单功能?
我看过这个帖子Mimic tabulate command from Stata in R,但是由于这个问题中的代码不包含gmodels 的库CrossTable,所以我无法应用它。输出看起来也不同。
【问题讨论】:
-
addmargins(table(read$hon, read$female))? -
我看到了这篇文章,但这看起来与我在帖子中提到的 stata 输出不同。
-
补充大卫的评论:
addmargins(table(read$hon, read$female, dnn = c("Hon", "Female"))) -
thx @DavidArenburg ,这就是我想要的。我在引用包
gmodels的链接帖子中进行了编辑。我的帖子似乎是重复的