user2806363
user2806363

Reputation: 2593

How to convert for loop to lapply in R?

I have for loop for reading files in directory and doing some computations on them. I want to replace my for loop with lapply to be able use parralel package to make my compuation parralel. would someone help me to convert this for loop to lapply ?

for (filename in dir(data.dir))
{


    filename = paste(data.dir,filename,sep="/")
    dfr=read.table(filename,header=TRUE)

    if (ncol(dfr) > 1)
    {
.
.
.

Upvotes: 1

Views: 369

Answers (2)

JeremyS
JeremyS

Reputation: 3525

files <- list.files(path="...") # fill in the path, if you only want say .txt files then add pattern="txt"
data.list <- lapply(files, function(x) read.table(x,header=T))

You now have a list of data.frames

res <- lapply(data.list, function(x) {if (ncol(x) > 1) {....}})

Upvotes: 1

Thomas
Thomas

Reputation: 44585

Replace for (filename in dir(data.dir)) {...} with lapply(dir(data.dir), function(filename) {...})

Presumably you'll need to add some kind of return value in there, but it's not clear from your code what the output of your loop is.

Upvotes: 4

Related Questions