Calculate median across multiple lists vertically

Viewed 70

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:

  • First position: 2
  • Second position: 5
  • Third position: 3

How can I achieve this in R? Thanks in advance.

4 Answers

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

Get all the individual lists together in one list using mget, combine them in a matrix and take row-wise median.

matrixStats::rowMedians(sapply(mget(ls(pattern = 'list')), unlist))
#[1] 2 5 3

Or keeping it in base R :

mat <- sapply(mget(ls(pattern = 'list')), unlist)
apply(mat, 1, median)

I had to change the data types a little bit to get it to work, might look at the other answers first, but this is what I did to get what you asked for. I put the values in vectors, and then in a data frame instead of a list, and then called the median() function on the respectable columns you wanted.

listA <- c(10, 5, 4)
listB <- c(2, 8, 3)
listC <- c(1, 5, 3)

test <- as.data.frame(rbind(listA, listB, listC))

median(test[,1])
[1] 2
median(test[,2])
[1] 5
median(test[,3])
[1] 3

An option with map and transpose

library(dplyr)
library(purrr)
mget(ls(pattern = ('^list[A-C]'))) %>% 
   transpose %>%
   map_dbl(~ flatten_dbl(.x) %>% median)
#[1] 2 5 3
Related