Say I have three lists, each one containing the result of a test:
listA <- list(10, 5, 4)
listB <- list(2, 8, 3)
listC <- list(1, 5, 3)
I want to find the median of those lists by position vertically. So the results for each position would be:
How can I achieve this in R? Thanks in advance.
You can use Map()
to combine the three lists vertically, and then compute each median by lapply()
.
sapply(Map(c, listA, listB, listC), median)
# [1] 2 5 3
You can also use transpose()
from purrr
.
library(purrr)
map_dbl(transpose(mget(ls(pattern = 'list'))), ~ median(flatten_dbl(.x)))
# [1] 2 5 3
Or using pmap()
:
pmap_dbl(mget(ls(pattern = 'list')), ~ median(c(...)))
# [1] 2 5 3