-1

I have a function f(x,y) where both the inputs are integers. Given a natural number K, I would like to evaluate f at all points in the set { (x,y) : 0 <= x <= K-1 , x < y <= K }. In other words, evaluating f at all feasible 0 <=x,y <= K which satisfy y>x.

I know this can be done with nested for loops but I am wondering if there is a more efficient way to do it through one of the apply functions perhaps.

mybrave
  • 1,662
  • 3
  • 20
  • 37
Exc
  • 173
  • 2
  • 2
  • 8
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Apr 27 '20 at 05:26

1 Answers1

1

Here is one way of doing what the question asks for. It's a simple double *apply loop with a function call in the inner most loop.

f <- function(x, y) {x + y + x*y}

K <- 10
sapply(0:(K - 1), function(x){
  sapply((x + 1):K, function(y) f(x, y))
})

This is easily rewritten as a function of K and f.

fun <- function(K, FUN){
  f <- match.fun(FUN)
  lapply(0:(K - 1), function(x){
    sapply((x + 1):K, function(y) f(x, y))
  })
}

fun(10, f)
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66