Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some 'cross apply' function in R?

Tags:

r

Is there some function in R of the form like:

crossApply(v1, v2, func)

that has the same functionality as:

ret = c()
i = 1
for (e1 in v1) {
  for (e2 in v2) {
    ret[i] <- func(e1,e2)
    i <- i + 1
  }
}
return(ret)

Thanks in advance.

like image 614
Derrick Zhang Avatar asked Oct 20 '25 13:10

Derrick Zhang


2 Answers

I think you may be looking for outer which isn't exactly what your code does, but it's close. Specifically, outer will return the matrix (i.e. the outer product) or each combination of the elements of its first two arguments.

You'd probably want to store the result and then extract the lower triangle as a vector. Something like this maybe:

rs <- outer(1:4,-(5:7),"+")
rs[lower.tri(rs,diag = TRUE)]
[1] -4 -3 -2 -1 -4 -3 -2 -4 -3
like image 162
joran Avatar answered Oct 23 '25 05:10

joran


An example

func <- function(x,y) {sqrt(x^2+y^2)}
v1 <- c(1,3,5)
v2 <- c(0,-4,-12)
ret <- outer(v1,v2,"func")

And you then have

> ret
     [,1]     [,2]     [,3]
[1,]    1 4.123106 12.04159
[2,]    3 5.000000 12.36932
[3,]    5 6.403124 13.00000

or if you want exactly what your for loops would produce

> as.vector(t(ret))
[1]  1.000000  4.123106 12.041595  3.000000  5.000000 12.369317  5.000000
[8]  6.403124 13.000000
like image 36
Henry Avatar answered Oct 23 '25 05:10

Henry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!