Vectorize a scalar function to work on any R object.
vectorize.RdRobust alternative to Vectorize function that accepts any function with two
or more arguments. Returns a function that will work an arbitrary number of vectors, lists or
data frames, though output may be unpredicatable in unusual applications. The
results are also intended to be more intuitive than Vectorize.
Arguments
- fun
a two or more argument function
- type
like
MARGINinapply, except thatc(1,2)is represented as a3instead. By default, willReducesingle dimensional data handle everything else row-wise.
Examples
vectorize(`+`)(c(1,2,3))
#> object
#> 6
vectorize(sum)(c(1,2,3),c(1,2,3))
#> [1] 2 4 6
# Compare these results to Vectorize, which does not vectorize sum at all.
Vectorize(sum)(c(1,2,3),c(1,2,3))
#> [1] 12
# Across data frame columns.
df<-data.frame(a=c(1,2,3),b=c(1,2,3))
vectorize(sum)(df$a,df$b)
#> [1] 2 4 6
# Once again, Vectorize gives a different result
Vectorize(sum)(df$a,df$b)
#> [1] 12
# Any combination of vectors, lists, matrices, or data frames an be used.
vectorize(`+`)(c(1,2,3),list(1,2,3),cbind(c(1,2,3)))
#> [1] 3 6 9