Domanda

I have the following function

myfunc <- function(x,myparam) {
     x <- do_sth(x, myparam)
     plot(x)
}

Then to be applied to these data:

files <- Sys.glob("myfile_no*.txt") # This is a vector

Currently I do the following:

for (i in 1:length(files)) {
    mf <- files[i]
    myfunc(mf,myparam=3);

}

How can I replace the for-loop above with apply or its other variations?

I tried this with error:

> apply(x,1, myfunc, myparam)
Error in apply(files, 1, myfunc, myparam = 3) : 
  dim(X) must have a positive length
Execution halted
È stato utile?

Soluzione

So, the obvious solution is not apply but lapply:

output_object <- lapply(files, myfunc, myparam = 3)

This also has the advantage of allowing you to use an 'anonymous' function if you want a slightly cleaner environment.

What I'm wondering, though, is why you want to? Is it an attempt to get away from perceived slowness in for loops? If so, you're not likely to see that great an improvement; people complaining "my for loop is slow" are normally complaining "I am trying a for-loop over a non-primitive data type" or "I am trying a for loop that iteratively adds to an object without a defined length". Those aren't the case here. The only thing I can think of that would improve your speed is to stop defining mf - simply call myfunc(files[i], myparam = 3).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top