0

I am used to use apply familiy functions to avoid for loop with R. In this context I was wondering it there is a way to avoid typing a bound variable. For example, say I want to do 100 times an operation do.call(myfun, args). With for I'd write:

res = seq(100)
for(i in seq(100)){res[i] = do.call(myfun, args)}

with apply I type:

res = sapply(seq(100), function(i) do.call(myfun, args))

I understand that sapply tries to apply the function to one argument, it is an element of seq(100), but is there a way to avoid this, because indeed this variable (here i) has no meaning neither utility ?

thanks for the insight

ClementWalter
  • 4,814
  • 1
  • 32
  • 54
  • you can do `sapply(seq(100), identity)`, or any other function in place of `identity`, no need for anonymous function – Rorschach Aug 13 '15 at 09:57
  • yes, identity is a function taking one argument; my case is when I want to make a given calculation a given number of times, ie repeted simulation with the same parameters; for example `res = sapply(seq(100), function(i) do.call(myfun, args) )` – ClementWalter Aug 13 '15 at 10:04
  • 2
    oh ok, you probably want `replicate`, ie `replicate(10, do.call(identity, list(1:10)))` – Rorschach Aug 13 '15 at 10:07
  • ok cool, as simple as that, I didn't know this function ! – ClementWalter Aug 13 '15 at 10:10

0 Answers0