Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when the iterable is NOT the first argument of the function

Tags:

r

sapply

apply

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.

like image 298
Heisenberg Avatar asked Mar 07 '14 23:03

Heisenberg


1 Answers

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))
like image 68
eddi Avatar answered Sep 28 '22 07:09

eddi