How to vectorize a subsetting function in R?

The problem is that filter takes vector inputs, so it will recycle the vectors in the Sepal.width and Sepal.length comparisons.

One way to do this would be to use map2 from the purrr package:

map2_dbl(sep_wid_vector, sep_len_vector, test_funct)

Of course you could then wrap this in a function. You might also want to consider passing in the data frame as a function parameter.


You can use Vectorize:

tv <- Vectorize(test_funct)

tv(sep_wid_vector, sep_len_vector)
# [1]  0.7  4.2 28.5

This is basically a wrapper around mapply. Be aware that under the hood you are running an *apply function, which is alos sort of a loop

Tags:

R

Dplyr