I have the table with 9 collumn, 8 of which presented by numeric data and last collumn is grouping variable with 3 categories. It looks like in example of the table below.
data.frame(var1=rnorm(9), var2=rnorm(9),
var3=rnorm(9), var4=rnorm(9),
group=rep(c('A','B','C'),each=3))
I tried to create a function to calculate statistic and p.value of T-test in three pairs in each collumn with numeric data. I had no problem with creating a function that generates result in list format. The goal is to get a table format of results ( statistic (t) and p.value) for every pair in each collumn.
CodePudding user response:
set.seed(1)
df <- data.frame(
var1 = rnorm(9),
var2 = rnorm(9),
var3 = rnorm(9),
var4 = rnorm(9),
group = rep(c('A', 'B', 'C'), each = 3)
)
df
#> var1 var2 var3 var4 group
#> 1 -0.6264538 -0.30538839 0.82122120 -1.47075238 A
#> 2 0.1836433 1.51178117 0.59390132 -0.47815006 A
#> 3 -0.8356286 0.38984324 0.91897737 0.41794156 A
#> 4 1.5952808 -0.62124058 0.78213630 1.35867955 B
#> 5 0.3295078 -2.21469989 0.07456498 -0.10278773 B
#> 6 -0.8204684 1.12493092 -1.98935170 0.38767161 B
#> 7 0.4874291 -0.04493361 0.61982575 -0.05380504 C
#> 8 0.7383247 -0.01619026 -0.05612874 -1.37705956 C
#> 9 0.5757814 0.94383621 -0.15579551 -0.41499456 C
nm_grp <- unique(df$group)
library(tidyverse)
grp_split <- combn(nm_grp, m = 2) %>%
data.frame() %>%
set_names(nm = map_chr(., paste0, collapse = ""))
l <- map(grp_split, ~ filter(df, group %in% .x))
res_list <- map(
.x = l,
.f = function(x)
map(
.x = select(x, where(is.numeric)),
.f = function(y)
t.test(y ~ x$group, data = x)
)
)
res_nm <- map(names(grp_split), ~paste0(.x, ": ", names(df[-5]))) %>% flatten_chr()
map_df(flatten(res_list), broom::glance) %>%
add_column(nm = res_nm, .before = 1)
#> # A tibble: 12 x 11
#> nm estim~1 estim~2 estim~3 stati~4 p.value param~5 conf.~6 conf.~7 method
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>
#> 1 AB: v~ -0.794 -0.426 0.368 -1.04 0.381 2.76 -3.35 1.76 Welch~
#> 2 AB: v~ 1.10 0.532 -0.570 1.00 0.388 3.10 -2.33 4.54 Welch~
#> 3 AB: v~ 1.16 0.778 -0.378 1.38 0.298 2.05 -2.36 4.67 Welch~
#> 4 AB: v~ -1.06 -0.510 0.548 -1.52 0.206 3.79 -3.03 0.912 Welch~
#> 5 AC: v~ -1.03 -0.426 0.601 -3.21 0.0736 2.22 -2.28 0.224 Welch~
#> 6 AC: v~ 0.238 0.532 0.294 0.383 0.725 3.32 -1.64 2.11 Welch~
#> 7 AC: v~ 0.642 0.778 0.136 2.45 0.104 2.61 -0.267 1.55 Welch~
#> 8 AC: v~ 0.105 -0.510 -0.615 0.156 0.884 3.64 -1.84 2.05 Welch~
#> 9 BC: v~ -0.232 0.368 0.601 -0.331 0.771 2.04 -3.19 2.72 Welch~
#> 10 BC: v~ -0.865 -0.570 0.294 -0.850 0.471 2.45 -4.56 2.83 Welch~
#> 11 BC: v~ -0.514 -0.378 0.136 -0.593 0.606 2.34 -3.77 2.74 Welch~
#> 12 BC: v~ 1.16 0.548 -0.615 1.99 0.117 3.97 -0.461 2.79 Welch~
#> # ... with 1 more variable: alternative <chr>, and abbreviated variable names
#> # 1: estimate, 2: estimate1, 3: estimate2, 4: statistic, 5: parameter,
#> # 6: conf.low, 7: conf.high
```
<sup>Created on 2022-08-23 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup>