从 R 中的 t 检验创建具有输出 table 的函数

Creating function with output table from t-test in R

我想编写一个函数以获得 t 检验的整洁输出 table,因为我正在进行大量 post-hoc t 检验,但是,编写函数不是我的强项适合所以我需要一些帮助。我当前的代码如下所示


library(tidyverse)
library(lsr)
library(broom)

t_table <- function(data$col, data$col) {

  t.test(data$col, data$col) %>%
    broom::tidy() %>%
    mutate(Cohens_d = cohensD(data$col, data$col)) %>% # calc. cohen's d
    mutate_at(vars(- c(p.value,method,alternative)), round, 2)
}

其中一个错误是:

Error in data$col : object of type 'closure' is not subsettable.

我假设 data 和 col 不是任何数据框和列的通用名称。

基本上我希望能够为每个变量指定任何数据框和列。我什至不确定这是否可行,因为这是我正在尝试创建的一个非常通用的功能,但我们将不胜感激任何帮助。

您的函数的输入参数应 a) 不同名且 b) 不应包含 $。除此之外,您的功能运行良好:

t_table <- function(col1, col2) {

  t.test(col1, col2) %>%
    broom::tidy() %>%
    mutate(Cohens_d = cohensD(col1, col2)) %>% # calc. cohen's d
    mutate_at(vars(- c(p.value,method,alternative)), round, 2)
}

set.seed(1)
t_table(rnorm(100), rnorm(100)+1/2)
  estimate estimate1 estimate2 statistic     p.value parameter conf.low conf.high                  method alternative Cohens_d
1    -0.35      0.11      0.46     -2.69 0.007745151    197.19    -0.61     -0.09 Welch Two Sample t-test   two.sided     0.38