gpt4 book ai didi

r - 如何使用 dplyr 内的函数或表达式对 dplyr 内的公式调用创建的 t.test 模型的属性进行变异?

转载 作者:行者123 更新时间:2023-12-02 04:32:32 31 4
gpt4 key购买 nike

 library(dplyr)
mtcars %>%
group_by(vs) %>%
do(tt=t.test(mpg~am, data=.)) %>%
mutate(t=tt$statistic, p=tt$p.value)

我已经对 mgp 进行了 t.test,相对于每个 vs. 我正在尝试提取 t.test 模型的属性并将它们排列在数据框中。我能够提取 p 值和 t 值或任何单长度属性。

输出:

Source: local data frame [2 x 4]
Groups: <by row>

vs tt t p
1 0 <S3:htest> -2.579484 0.034481482
2 1 <S3:htest> -3.764735 0.004436935

现在,如果我想使用下面的代码提取平均组差异:

mtcars %>% 
group_by(vs) %>%
do(tt=t.test(mpg~am, data=.)) %>%
mutate(t=tt$statistic, p=tt$p.value, delta=diff(tt$estimate))

或者甚至当我只想访问组 0 的平均值时

     mutate(t=tt$statistic, p=tt$p.value, delta=tt$estimate[0])

R 抛出以下错误:

  Error: object 'tt' not found

似乎 tt 是在不同的环境中求值的,在该环境中应用表达式或函数时未定义它。我也尝试过使用 funs 但没有成功。有人可以在这里解释一下吗?

最佳答案

您还可以使用broom包,它是为data.frames内部的统计测试而设计的:

library(broom)
library(dplyr)
mtcars %>% group_by(vs) %>%
do(tidy(t.test(mpg~am, data = .)))

Source: local data frame [2 x 9]
Groups: vs [2]

vs estimate estimate1 estimate2 statistic p.value parameter
(dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl)
1 0 -4.700000 15.05000 19.75000 -2.579484 0.034481482 7.486364
2 1 -7.628571 20.74286 28.37143 -3.764735 0.004436935 9.017524
Variables not shown: conf.low (dbl), conf.high (dbl)

关于r - 如何使用 dplyr 内的函数或表达式对 dplyr 内的公式调用创建的 t.test 模型的属性进行变异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34057983/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com