简体   繁体   中英

faster alternative to for loop with two-argument function

I have a list of csv files called sourcefiles, and I want to apply a function with two arguments to all of files in sourcefiles. Here's what I'm doing now:

 for (n in 1:length(sourcefiles)){
      clcc(DT, n)
    }

Is there any better way?

Thanks!

You can use lapply function:

lapply(X=aList, FUN=aFunction, otherParameters)

This function call aFunction for every item of the aList passing it as a first parameter and otherParameters as the other parameters.

The problem here is that your function clcc does not take the sourcefile as first parameter, but there is an easy workaround. If the formal name of the first parameter of the function clcc is DT (or whatever), you can call lapply by setting the name of it:

lapply(X=sourcefiles, FUN=clcc, DT=DT)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM