0

我正在使用rstatix. 我可以为每个变量生成我想要的结果,但无法遍历多个变量以一次性生成一个链接表。

require(dplyr)
require(rstatix)
data <- data.frame(group=rep(c(1,2),5), v1=rnorm(10),v2=rnorm(10))

data %>%
  t_test(v1 ~ group,detailed = TRUE) %>%
  adjust_pvalue() %>%
  add_significance(cutpoints = c(0, 1e-04, 0.001, 0.01, 0.05, 1),
                   symbols = c("****", "***", "**", "*", "ns")) %>%
  select(c(".y.","estimate1","estimate2","statistic","p.adj","p.adj.signif")) %>%
  dplyr::rename(variable = .y.,
                'training' = estimate1,
                'test' = estimate2,
                't-test'=statistic,
                p=p.adj,
                sl=p.adj.signif)

这失败了:

vars <- c("V1", "V2")

bt <- character(0)
for(i in 1:length(vars)){
bt_temp <- data %>%
  t_test(vars[i] ~ group, detailed = TRUE) %>%
  adjust_pvalue() %>%
  add_significance(cutpoints = c(0, 1e-04, 0.001, 0.01, 0.05, 1),
                   symbols = c("****", "***", "**", "*", "ns")) %>%
  select(c(".y.","estimate1","estimate2","statistic","p.adj","p.adj.signif")) %>%
  dplyr::rename(variable = .y.,
                'training' = estimate1,
                'test' = estimate2,
                't-test'=statistic,
                p=p.adj,
                sl=p.adj.signif)

bt <- rbind(bt, bt_temp)

4

1 回答 1

0

关键是用来paste0拼凑一个字符串,然后您可以将其转换为公式。在下面的解决方案中,我已将您的 for 循环转换为更纯粹的地图。

require(dplyr)
require(rstatix)
data <- data.frame(group=rep(c(1,2),5), v1=rnorm(10),v2=rnorm(10))  
vars <- c("v1", "v2")
    
my_new_function <- function(var){
    data %>% 
        t_test(as.formula(paste0(var, " ~ group")), detail = TRUE) %>% 
        adjust_pvalue() %>%
        add_significance(cutpoints = c(0, 1e-04, 0.001, 0.01, 0.05, 1),
                         symbols = c("****", "***", "**", "*", "ns")) %>%
        select(c(".y.","estimate1","estimate2","statistic","p.adj","p.adj.signif")) %>%
        dplyr::rename(variable = .y.,
                      'training' = estimate1,
                      'test' = estimate2,
                      't-test'=statistic,
                      p=p.adj,
                      sl=p.adj.signif)
}

vars %>% purrr::map(my_new_function) %>% bind_rows

你有一个无用的拼写错误vars,混合了大写和小写“v/V”。如果你真的想使用 for 循环,你需要添加一个缺少的结束 }。另外,创建

bt_temp <- vector("list", length(vars))

在你的循环之前。在循环内部,将结果分配给bt_temp[[i]]. 在循环之后绑定行一次。如果您尝试bt在每次迭代中增长,那么当有很多迭代时,您的循环会很慢。

于 2020-12-16T15:39:18.267 回答