'How to apply variables to calcute them using purrr in R

Here are a part of my data

df <- data.frame(
  Group1 = rep(c('A', 'A'), 50),
  Group2 = rep(c('A', 'B'), 50),
  Group3 = rep(c('A', 'B'), 50),
  Value1 = rnorm(50,12,4),
  Value2 = rnorm (50,10,4),
  Value3 = rnorm (50,10,4)
)

Group1 corresponds to value1, Group2 corresponds to Value2 and Group3 corresponds to Value 3. I want to use the t.test to get a table ( not a list) for means and p-values for each group using Purrr.

I have used the following codes using purrr.

df %>% 
  split.default(rep_len(1:3, ncol(.))) %>% 
pmap(~t.test(.x,.y))


Solution 1:[1]

With tidyverse, we may reshape to 'long' with pivot_longer and then do the t.test

library(dplyr)
library(tidyr)
df %>%
   pivot_longer(cols = everything(), names_to = c( ".value", "grp"),
     names_pattern = "(\\D+)(\\d+)") %>% 
  group_by(grp) %>%
   summarise(out = if(n_distinct(Group) > 1) 
   list(t.test(Value ~ Group) %>% broom::tidy(.)) else list(NULL)) %>% 
  unnest_wider(out)

-output

# A tibble: 3 × 11
  grp   estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high method                  alternative
  <chr>    <dbl>     <dbl>     <dbl>     <dbl>   <dbl>     <dbl>    <dbl>     <dbl> <chr>                   <chr>      
1 1      NA          NA        NA       NA     NA           NA      NA       NA     <NA>                    <NA>       
2 2      -0.0796     10.8      10.9     -0.114  0.909       98.0    -1.46     1.30  Welch Two Sample t-test two.sided  
3 3      -1.42        8.53      9.96    -2.14   0.0350      94.6    -2.75    -0.102 Welch Two Sample t-test two.sided  

Or using the purrr

library(purrr)
library(stringr)
df %>% 
  split.default(str_remove(names(.), "\\D+")) %>% 
  map_dfr(~ .x %>% 
        rename_with(~ str_remove(.x, "\\d+"), everything()) %>% 
     {if(n_distinct(.x$Group) > 1) t.test(Value ~ Group, data = .)
    } %>%
     broom::tidy(.), .id = "grp")

-output

# A tibble: 2 × 11
  grp   estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high method                  alternative
  <chr>    <dbl>     <dbl>     <dbl>     <dbl>   <dbl>     <dbl>    <dbl>     <dbl> <chr>                   <chr>      
1 2      -0.0796     10.8      10.9     -0.114  0.909       98.0    -1.46     1.30  Welch Two Sample t-test two.sided  
2 3      -1.42        8.53      9.96    -2.14   0.0350      94.6    -2.75    -0.102 Welch Two Sample t-test two.sided  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1