【问题标题】:Crosstable similar to Stata in R类似于 R 中的 Stata 的交叉表
【发布时间】: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 变量honfemale

想要的结果看起来像这样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 的链接帖子中进行了编辑。我的帖子似乎是重复的

标签: r crosstab reshape2


【解决方案1】:
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))

【讨论】:

    猜你喜欢
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多