[英]Calling var() from purrr's pmap() returns NA
I am trying to use pmap()
from the purrr
package to simplify my code. 我试图使用
purrr
包中的pmap()
来简化我的代码。
I have a list of vectors x
; 我有一个矢量列表
x
; all the vectors are the same length. 所有向量都是相同的长度。 I want to find the mean and variance of all nth elements across all vectors in the list.
我想找到列表中所有向量的所有第n个元素的均值和方差。 That is, I want the mean and variance of all the first elements, all the second elements, and so on.
也就是说,我想要所有第一个元素的均值和方差,所有第二个元素,等等。
Before the tidyverse
, I would convert x
to a matrix and use apply()
. 在
tidyverse
之前,我会将x
转换为矩阵并使用apply()
。
x <- list(1:10, 1:10, 1:10)
x_matrix <- do.call(cbind, x)
apply(x_matrix, 1, mean)
## [1] 1 2 3 4 5 6 7 8 9 10
apply(x_matrix, 1, var)
## [1] 0 0 0 0 0 0 0 0 0 0
pmap()
should allow this without the matrix conversion. pmap()
应该允许这个没有矩阵转换。 pmap_dbl()
can replace the apply()
and mean()
calculation above. pmap_dbl()
可以替换上面的apply()
和mean()
计算。
library(purrr)
pmap_dbl(x, mean)
## [1] 1 2 3 4 5 6 7 8 9 10
However, I cannot get pmap_dbl()
and var()
and calculation to work. 但是,我不能让
pmap_dbl()
和var()
和计算工作。 I get NA
for every variance. 我得到每个方差的
NA
。
pmap_dbl(x, var)
## [1] NA NA NA NA NA NA NA NA NA NA
What am I missing? 我错过了什么?
We can use ~
and then with ...
get the elements, and apply the function 我们可以使用
~
然后用...
获取元素,然后应用函数
pmap_dbl(x, ~ var(c(...)))
The reason for different behavior is the difference in the number of parameters in mean
and var
. 不同行为的原因是
mean
和var
中参数数量的差异。 In mean
, after the object x
, other parameters go into ...
, while in var
, it is not the case, there is x
, there is y
etc. mean
,在对象x
,其他参数进入...
,而在var
,情况并非如此,有x
,有y
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.