The problem with your approach is that you're trying to pass a matrix (B
) to your function foo
, which is expecting two vectors (x
and y
).
You could try something like this instead:
sapply(1:ncol(A), function(i) sd(B[as.logical(abs(A[,i])),i]))
[1] 1.5275252 0.7071068
Which is basically just a loop...
Another approach would be if your A
and B
objects are dataframes, you can use mapply
:
A <- as.data.frame(A)
B <- as.data.frame(B)
mapply(foo, A,B)
V1 V2
1.5275252 0.7071068
Benchmarking the two approaches, the sapply
route is maybe twice as fast. I can imagine that this is because sapply
is just taking a vector of integers as arguments and processing matrices whereas the mapply
approach is taking dataframes as arguments (dataframes are slower than matrices and more information to pass the loop than just a single index value). Details:
Unit: microseconds
expr min lq median uq max neval
sapply(1:ncol(A), function(i) sd(B[as.logical(abs(A[, i])), i])) 101.997 110.080 113.929 118.5480 1515.319 1000
mapply(foo, A2, B2) 191.292 200.529 207.073 215.1555 1707.380 1000