我已经成功地对一些函数进行了向量化处理,这对于编写简洁的代码、避免循环和提高速度非常有帮助。
然而,我无法将任何基于函数输入对数据框进行子集化筛选(subset)的函数向量化。
示例
例如,当该函数接收到元素时,它能够正常工作。
test_funct <- function(sep_wid, sep_len) {
iris %>% filter(Sepal.Width > sep_wid & Sepal.Length < sep_len) %>% .$Petal.Width %>% sum
}
test_funct(4, 6)
# [1] 0.7 # This works nicely
但是在试图将向量作为此函数的输入提供时:
sep_wid_vector <- c(4, 3.5, 3)
sep_len_vector <- c(6, 6, 6.5)
test_funct(sep_wid_vector, sep_len_vector)
[1] 9.1
但期望的输出是与输入向量长度相同的向量,就好像函数在每个向量的第一个元素上运行,然后是第二个元素,第三个元素等等。
# 0.7 4.2 28.5
为了方便起见,这里的输出好像是分别运行的
test_funct(4, 6) # 0.7
test_funct(3.5, 6) # 4.2
test_funct(3, 6.5) # 28.5
我该如何将一个根据其输入子集数据的函数向量化,以便它可以接收向量输入?
purrr::map2_dbl
。为了完整起见,mapply(test_funct, sep_wid_vector, sep_len_vector)
也可以使用。 - stevec