简体   繁体   English

用purrr和reduce按行计算向量列表的值

[英]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返回了滞后向量的列表。

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

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

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

[[3]] [1] NA NA 1 2 3 4 5 6 7 8 [[3]] [1]不适用不适用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 [1]不适用不适用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 5.5

This is not the answer I'm interested in. How do I do that using purrr? 这不是我感兴趣的答案。如何使用purrr做到这一点?

You could use a variant of pmap to loop through all three vectors simultaneously. 您可以使用pmap的变体同时遍历所有三个向量。 Because mean takes a vector of numbers, though, I used an anonymous function to concatenate the three elements together via c . 由于mean是一个数字向量,因此我使用了一个匿名函数通过c将三个元素连接在一起。

pmap_dbl returns a vector of numbers. pmap_dbl返回数字向量。

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. 开发版本添加了..1类型编码,并带有波浪号以引用每个列表。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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