gpt4 book ai didi

r - 如何在我的数据框中进行大量的 t.test(多组/结果,多定量变量)?

转载 作者:行者123 更新时间:2023-12-01 09:40:52 27 4
gpt4 key购买 nike

通过在 R 中运行多个 t.test(根据多个定量变量比较多个组),我想在 R 中得到这样的结果:

excel sheet

我尝试并修改了此处提供的解决方案: dplyr summarise multiple columns using t.test

library(dplyr)
library(tidyr)
data(mtcars)


vars_to_test <- c("disp","hp","drat","wt","qsec")
iv <- c("vs", "am")


mtcars %>%
summarise_each_(
funs_(
sprintf("stats::t.test(.[%s == 0], .[%s == 1])$p.value",iv,iv)
),
vars = vars_to_test)

这是输出:

     disp_$..1      hp_$..1  drat_$..1      wt_$..1    qsec_$..1    disp_$..2   hp_$..2    drat_$..2     wt_$..2 qsec_$..2
1 2.476526e-06 1.819806e-06 0.01285342 0.0007281397 3.522404e-06 0.0002300413 0.2209796 5.266742e-06 6.27202e-06 0.2093498

我面临多个问题:

  • (1) 我有两个警告消息,我不知道两个如何解决
Please use summarise_if(), summarise_at(), or summarise_all() instead: 

- To map `funs` over all variables, use summarise_all()
- To map `funs` over a selection of variables, use summarise_at()
This warning is displayed once per session.
2: funs_() is deprecated.
Please use list() instead
  • (2) 如何让每个组/结果占一行?
  • (3) 如何通过组名称更改“1”(第二行的第一个字符)(即:本例中的“vs”和“am”)?
  • (4) 如何将此输出导出为数据框(如我开始的示例所示)

非常感谢您的帮助!

最佳答案

library(tidyverse)

vars_to_test <- c("disp","hp","drat","wt","qsec")
iv <- c("vs", "am")

expand.grid(vars_to_test, iv, stringsAsFactors = F) %>% # create pairs of variables
rowwise() %>% # for each pair
mutate(p_val = t.test(mtcars[,Var1] ~ mtcars[,Var2])$p.value) %>% # get p value from t.test
spread(Var1, p_val) # reshape output

# # A tibble: 2 x 6
# Var2 disp drat hp qsec wt
# <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 am 0.000230 0.00000527 0.221 0.209 0.00000627
# 2 vs 0.00000248 0.0129 0.00000182 0.00000352 0.000728

关于r - 如何在我的数据框中进行大量的 t.test(多组/结果,多定量变量)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60505256/

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