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)

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.