Especially when dealing with pipes that require multiple inputs (we don't have Haskell's Arrows here), I find it easier to reason by types/signatures first, then encapsulate logic in functions (which you can unit test), then write a concise chain.
In this case you want to compare all possible pairs of vectors, so I would set a goal of writing a function that takes a pair (i.e. a list of 2) of vectors and returns the 2-way t.test of them.
Once you've done this, you just need some glue. So the plan is:
- Write function that takes a list of vectors and performs the 2-way t-test.
- Write a function/pipe that fetches the vectors from mtcars (easy).
- Map the above over the list of pairs.
It's important to have this plan before writing any code. Things are somehow obfuscated by the fact that R is not strongly typed, but this way you reason about "types" first, implementation second.
Step 1
t.test takes dots, so we use purrr:lift
to have it take a list. Since we don't want to match on the names of the elements of the list, we use .unnamed = TRUE
. Also we make it extra clear we're using the t.test
function with arity of 2 (though this extra step is not needed for the code to work).
t.test2 <- function(x, y) t.test(x, y)
liftedTT <- lift(t.test2, .unnamed = TRUE)
Step 2
Wrap the function we got in step 1 into a functional chain that takes a simple pair (here I use indexes, it should be easy to use cyl factor levels, but I don't have time to figure it out).
doTT <- function(pair) {
mtcars %>%
split(as.character(.$cyl)) %>%
map(~ select(., mpg)) %>%
extract(pair) %>%
liftedTT %>%
broom::tidy
}
Step 3
Now that we have all our lego pieces ready, composition is trivial.
1:length(unique(mtcars$cyl)) %>%
combn(2) %>%
as.data.frame %>%
as.list %>%
map(~ doTT(.))
$V1
estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high
1 6.920779 26.66364 19.74286 4.719059 0.0004048495 12.95598 3.751376 10.09018
$V2
estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high
1 11.56364 26.66364 15.1 7.596664 1.641348e-06 14.96675 8.318518 14.80876
$V3
estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high
1 4.642857 19.74286 15.1 5.291135 4.540355e-05 18.50248 2.802925 6.482789
There's quite a bit here to clean up, mainly using factor levels and preserving them in the output (and not using globals in the second function) but I think the core of what you wanted is here. The trick not to get lost, in my experience, is to work from the inside out.