1

I have two lists and a function, like this:

ms <- c(1, 2, 3)
ns <- c(4, 5)
f <- function(m, n) {
    return result of some computation involving m and n
}

I want to get a table like this, where each entry is obtained by applying the function to each pair of elements in rows and cols:

         4       5
-------------------
1 | f(1, 4) f(1, 5)
2 | f(2, 4) f(2, 5)
3 | f(3, 4) f(3, 5)

How do I do this? I don't want to use for loops. I assume there is a way to do this using some form of apply.

2
  • 1
    Just fyi, when you change the names of all the variables in the question it makes the answers look like nonsense. Best to tell the answerers in a comment under their answer when you change things, as they do not get notified of question edits Commented Jan 21, 2015 at 19:07
  • 1
    Okay, thanks. I figured it wouldn't matter since I saw what you meant. I guess that doesn't help the next guy much, though. I will keep that in mind in the future. Commented Jan 21, 2015 at 19:12

1 Answer 1

3

You could get the result using %*%

rows%*%t(cols)

Or

 tcrossprod(rows, cols)

Update

Based on the edited OP's post,

outer(rows, cols, FUN=f)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.