How to calculate the average value of two lists for each row

advertisements

I have two lists as below:

l1 <- list(a=1, b=2, c=3)
l2 <- list(a=4, b=5, c=6)

I want to calculate the mean value of the two lists for each row and assign the result to a new list. Like below:

l3 <- mean(l1, l2)

How can I achieve this in R?


We can use Map

Map(function(x,y) mean(c(x,y)), l1, l2)


Or with map2 from purrr

purrr::map2(l1, l2, ~ mean(c(.x, .y)))


Or using tidyverse

library(tidyverse)
bind_rows(l1, l2) %>%
      summarise_all(mean) %>%
      unlist() %>%
      relist(., skeleton = l1)


Or another option is

relist((unlist(l1) + unlist(l2))/2, skeleton= l1)

NOTE: All the solutions return a list as the OP mentioned in the post