0

This should be simple, but I can't work it out ...

I want to apply a function, eg. mean to each of the lower lists, eg. I want to return

$1

$1$a [1] value_of_mean 1

$1$b [1] value_of_mean 2

$2

$2$a [1] value_of_mean 3

$2$b [1] value_of_mean 4

I am trying to use the purrr package

require(purrr)    
mylist <- list("1"=list(a=runif(10), b=runif(10)), "2"=list(a=runif(10), b=runif(10)))
        map(mylist, mean)
user1420372
  • 2,077
  • 3
  • 25
  • 42

2 Answers2

2

You can call map twice to accomplish this. This will work through each list in the top-level list and perform the mean on each element of that top-level list, i.e., the bottom-level lists:

mylist %>% map(~ map(.x, mean))

that gives you this:

$`1`
$`1`$a
[1] 0.5734347

$`1`$b
[1] 0.5321065


$`2`
$`2`$a
[1] 0.483521

$`2`$b
[1] 0.5138651
tbradley
  • 2,210
  • 11
  • 20
1

You don't have to use map twice, as modify_depth was introduced to tidy-up the double map call.

library(purrr)

set.seed(123)

mylist <- list("1"=list(a=runif(10), b=runif(10)), "2"=list(a=runif(10), b=runif(10)))

modify_depth(mylist, 2, mean)

resulting in:

> modify_depth(mylist, 2, mean)
$`1`
$`1`$a
[1] 0.5782475

$`1`$b
[1] 0.5233693


$`2`
$`2`$a
[1] 0.6155837

$`2`$b
[1] 0.537858

This is the same as

mylist %>% map(~ map(.x, mean))

resulting in:

> mylist %>% map(~ map(.x, mean))
$`1`
$`1`$a
[1] 0.5782475

$`1`$b
[1] 0.5233693


$`2`
$`2`$a
[1] 0.6155837

$`2`$b
[1] 0.537858
Jake Kaupp
  • 7,892
  • 2
  • 26
  • 36