根据来自另一个变量的 bin 拆分一个变量

机器算法验证 r 回归 直方图
2022-03-31 13:31:32

我有研究中几个参与者的连续数据“A”、二进制分类数据“O”、性别/性别和年龄。

R 中的线性模型显示 A 和年龄之间没有相关性。我现在想按年龄将 A 分组,看看各组之间是否存在差异。我知道 R 中的 'hist' 和 'split' ,但这些并不能满足我的需要。

(1) 如何根据年龄(18 至 27、28 至 37 等)将 A 分成组。

(2) 完成后,我将使用χ2测试?

(3) 我是否也可以使用计数在同一组中测试 O?

1个回答
> A   <- round(rnorm(100, 100, 15), 2)       # generate some data
> age <- sample(18:65, 100, replace=TRUE)
> sex <- factor(sample(0:1, 100, replace=TRUE), labels=c("f", "m"))

# 1) bin age into 4 groups of similar size
> ageFac <- cut(age, breaks=quantile(age, probs=seq(from=0, to=1, by=0.25)),
+               include.lowest=TRUE)

> head(ageFac)
[1] (26,36.5] (26,36.5] (36.5,47] [18,26]   [18,26]   [18,26]  
Levels: [18,26] (26,36.5] (36.5,47] (47,65]

> table(ageFac)   # check group size
ageFac
[18,26] (26,36.5] (36.5,47]   (47,65] 
     27        23        26        24

# 2) test continuous DV in age-groups
> anova(lm(A ~ ageFac))
Analysis of Variance Table
Response: A
          Df  Sum Sq Mean Sq F value Pr(>F)
ageFac     3    15.8   5.272  0.0229 0.9953
Residuals 96 22099.2 230.200               

# 3) chi^2-test for equal distributions of sex in age-groups    
> addmargins(table(sex, ageFac))
     ageFac
sex   [18,26] (26,36.5] (36.5,47] (47,65] Sum
  f        11        10        12      11  44
  m        16        13        14      13  56
  Sum      27        23        26      24 100

> chisq.test(table(sex, ageFac))
        Pearson's Chi-squared test
data:  table(sex, ageFac) 
X-squared = 0.2006, df = 3, p-value = 0.9775