7

The problem is quite simple yet I can't find the answer.

I have myfun <- function(x, y). How can I sapply this function over a list of y?

To apply over x I would do this

iterables <- 1:10
sapply(iterables, myfun, y)

But I want the iterables to be y instead.

Filburt
  • 17,626
  • 12
  • 64
  • 115
Heisenberg
  • 8,386
  • 12
  • 53
  • 102

1 Answers1

8

You have several options - e.g. one mentioned by sgibb which relies on how R interprets function arguments, i.e. that myfun(y, x = x) is the same as myfun(x, y).

I prefer creating anonymous functions since it's easier to understand what's happening:

sapply(iterables, function(iter) myfun(x, iter))
eddi
  • 49,088
  • 6
  • 104
  • 155
  • If `myfun` has, say, 5 arguments, can I do this? `sapply(iterables, function(iter) myfun(x1, x2, x3, iter, x4)`? – Heisenberg Mar 07 '14 at 23:47