Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
222 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...