首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用R,是否有可能得到一个不存在数据的频率表?

使用R,是否有可能得到一个不存在数据的频率表?
EN

Stack Overflow用户
提问于 2013-04-17 16:36:11
回答 1查看 208关注 0票数 1

我正在编制一些人口统计表,包括种族、性别和族裔。其中一个表格是按族裔划分的性别和种族交叉表(西班牙裔/非西班牙裔)。到目前为止,没有西班牙裔参与这项研究,但表格需要制作并发送给感兴趣的各方(即监管机构)。

然而,我未能为该报告提出一份表格。显然,该表将全部为零,但它根本没有产生。这似乎是试图计算不存在的东西的局限性.

以下是我列举的例子数据:

代码语言:javascript
复制
race.in <- read.table(
text = "race eth sex
b   n   f
b   n   f
b   n   f
w   n   f
w   n   m
w   n   m
a   n   m
a   n   m
a   n   f
ai  n   m
ai  n   f
ai  n   m", header = TRUE)

attach(race.in)

race.levels <- c("b", "w", "a", "ai", "nh") 
eth.levels  <- c("h", "n")  # hispanic , not hispanic
sex.levels  <- c("m", "f")


#  this table is fine
table(factor(race, levels = race.levels), factor(sex, levels = sex.levels) )

#  this table is fine
table(factor(eth, levels = eth.levels), factor(sex, levels = sex.levels) )

#  table of race and ethnicity by sex
by(race.in, sex, FUN = function(X)  table(factor(race, levels = race.levels), factor(eth, levels = eth.levels) ))  

#  produces NULL for table for levels of "h"
by(race.in, factor(eth, levels = eth.levels), FUN = function(X)  table(factor(race, levels = race.levels), factor(sex, levels = sex.levels) ))

有没有办法制作一张零表?我知道这很愚蠢,但我们必须报告这件事,即使没有这组条件的数据.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-17 16:49:55

我不清楚为什么您不只是在data.frame中考虑变量。这使得创建表更加容易。

代码语言:javascript
复制
race.in$race <- factor(race.in$race, race.levels)
race.in$eth <- factor(race.in$eth, eth.levels)
race.in$sex <- factor(race.in$sex, sex.levels)
table(race.in)
table(race.in[c(1, 3, 2)])
# , , eth = h
# 
#     sex
# race m f
#   b  0 0
#   w  0 0
#   a  0 0
#   ai 0 0
#   nh 0 0
# 
# , , eth = n
# 
#     sex
# race m f
#   b  0 3
#   w  2 1
#   a  2 1
#   ai 2 1
#   nh 0 0

您可能还对探索ftable函数(对于“平面”表)感兴趣。例如:

代码语言:javascript
复制
> ftable(x=race.in, row.vars=1, col.vars=2:3)
     eth h   n  
     sex m f m f
race            
b        0 0 0 3
w        0 0 2 1
a        0 0 2 1
ai       0 0 2 1
nh       0 0 0 0
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16065501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档