R中的新手。考虑到这就是我的情况:(实际上我的实际情况要复杂得多)
set.seed(100)
df = data.frame(SEX=sample(c("M","F"),100,replace=TRUE),BW = rnorm(100,80,2))
[一列是性别(男性和女性),另一列是体重(体重)。我要测试男性的体重正常性和女性的体重正常性。然后,我可以分别测试方差的相等性。最后,针对这种情况进行T检验或其他检验。但是在这种情况下不能使用shapiro.test
。 (例如shapiro.test(BW~SEX,data=df)
)
我该怎么办?我不想分离数据框架或创建新的子集。
预先感谢〜!
哦,我自己弄清楚了...使用此代码
with(df, shapiro.test(BW[SEX == "M"]))
with(df, shapiro.test(BW[SEX == "F"]))
我很高兴我可以学到更多!
这里详细描述了此问题的“ tidyverse”解决方案:Running a model on separate groups。
简短地使用您的数据:
library(dplyr) # for mutate
library(tidyr) # for nest/unnest
library(purrr) # for map
library(broom) # for glance
df %>%
nest(data = c(BW)) %>%
mutate(model = map(data, ~ shapiro.test(.x$BW)),
g = map(model, glance)) %>%
unnest(g)
结果:
# A tibble: 2 x 6
SEX data model statistic p.value method
<fct> <list<df[,1]>> <list> <dbl> <dbl> <chr>
1 F [50 x 1] <htest> 0.982 0.639 Shapiro-Wilk normality test
2 M [50 x 1] <htest> 0.980 0.535 Shapiro-Wilk normality test