首页 > 解决方案 > 将数据帧分成块然后应用函数

问题描述

我有一个(大)数据集,如下所示:-

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,但它不起作用。

关于如何去做的任何想法?

标签: rdataframesubsetlapply

解决方案


这是tidyverse使用mapfrom的解决方案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 

推荐阅读