r - 将数据帧分成块然后应用函数
问题描述
我有一个(大)数据集,如下所示:-
dat <- data.frame(m=c(rep("a",4),rep("b",3),rep("c",2)),
n1 =round(rnorm(mean = 20,sd = 10,n = 9)))
g <- rnorm(20,10,5)
dat
m n1
1 a 15.132
2 a 17.723
3 a 3.958
4 a 19.239
5 b 11.417
6 b 12.583
7 b 32.946
8 c 11.970
9 c 26.447
g
我想用向量对每个“m”类别进行t检验
n1.a <- c(15.132,17.723,3.958,19.329)
我需要做一个像t.test(n1.a,g)
我最初考虑将它们分解为列表使用split(dat,dat$m)
然后使用lapply
,但它不起作用。
关于如何去做的任何想法?
解决方案
这是tidyverse
使用map
from的解决方案purrr
:
dat %>%
split(.$m) %>%
map(~ t.test(.x$n1, g), data = .x$n1)
或者,使用lapply
你提到的,它将把你所有的 t-test 统计数据存储在一个列表中(或者使用更短的版本by
,感谢@markus):
dat <- split(dat, dat$m)
dat <- lapply(dat, function(x) t.test(x$n1, g))
或者
dat <- by(dat, m, function(x) t.test(x$n1, g))
这给了我们:
$a
Welch Two Sample t-test
data: .x$n1 and g
t = 1.5268, df = 3.0809, p-value = 0.2219
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-11.61161 33.64902
sample estimates:
mean of x mean of y
21.2500 10.2313
$b
Welch Two Sample t-test
data: .x$n1 and g
t = 1.8757, df = 2.2289, p-value = 0.1883
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-7.325666 20.863073
sample estimates:
mean of x mean of y
17.0000 10.2313
$c
Welch Two Sample t-test
data: .x$n1 and g
t = 10.565, df = 19, p-value = 2.155e-09
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
7.031598 10.505808
sample estimates:
mean of x mean of y
19.0000 10.2313
推荐阅读
- bitcoin - 矿池挖矿为什么不能同时在多个矿池中挖矿?
- ios - WKWebView 只允许 DOM 主体内的点击事件 [Objective-C]
- java - 试图解决一个简单的RPG游戏
- python-jira - 有没有办法使用来自 python 的批量查询来识别非 eistsne JIRA 问题?
- python - 使用随机森林的销售订单交货时间预测
- typo3 - TYPO3 v8 中非管理员用户的权限问题
- node.js - node.js 路由另一个 js 文件
- arrays - 如何在C中修改函数内的数组
- regex - 如何进行匹配正则表达式的部分替换?
- sql - sqlcmd 中的编译器错误,但 sql live 中没有错误