简体   繁体   中英

Calculating values of a list of vectors by rows with purrr and reduce

I have this map here that returns a list of vectors of lags, using purrr:map.

purrr:map(0:2,~ lag(1:10, .x))

[[1]] [1] 1 2 3 4 5 6 7 8 9 10

[[2]] [1] NA 1 2 3 4 5 6 7 8 9

[[3]] [1] NA NA 1 2 3 4 5 6 7 8

I'm interested in calculating averages for rows if those vectors were combined into a tibble.

I know I can sum rows using rows. So, for example,

reduce(map(0:2,~ lag(1:10, .x)), `+`)

[1] NA NA 6 9 12 15 18 21 24 27

However, when I try:

reduce(map(0:2,~ lag(1:10, .x)), ~ mean(.x, na.rm=T))

5.5

This is not the answer I'm interested in. How do I do that using purrr?

You could use a variant of pmap to loop through all three vectors simultaneously. Because mean takes a vector of numbers, though, I used an anonymous function to concatenate the three elements together via c .

pmap_dbl returns a vector of numbers.

map(0:2, ~lag(1:10, .x) ) %>%
     pmap_dbl( function(a, b, c) mean( c(a, b, c), na.rm = TRUE) )

[1] 1.0 1.5 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

The development version has added ..1 type coding with the tilde to refer to each list.

map(0:2, ~lag(1:10, .x) ) %>%
     pmap_dbl( ~mean( c(..1, ..2, ..3), na.rm = TRUE) )

中间数据帧看起来不太漂亮,但仍可以按预期工作:

purrr::map(0:2,~ lag(1:10, .x)) %>% as.data.frame() %>% rowMeans(na.rm=TRUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM