mks212
mks212

Reputation: 921

Using Apply Functions In Place of For Loop In R

I am pushing ahead in R and have used lapply for the first time successfully in loading files in a function called ImportData(). The working function is:

AllData <- lapply(files, function(i){
    read.csv(i, stringsAsFactors = FALSE)
  })

AllData is list containing 4 data frames. In the future, it will contain more.

There are two more for loops in the function that I'd like to replace with lapply. The first is a loop that combines the Date and Time Columns into one timestamp. The i is throwing me off in creating the apply function.

  for (i in 1:length(AllData))
   {
    AllData[[i]]$Date <- strptime(paste(AllData[[i]]$Date, AllData[[i]]$Time), "%m/%d/%y %H:%M:%S")
    AllData[[i]] <- AllData[[i]][-2]
    }

The last loop is this. names(AllData) is a character vector of length 4.

  for (i in 1:length(names(AllData)))
  {
    cat("Time Frame: ", names(AllData)[i], "\n")
    trade(AllData[[i]])
  }

What is throwing me in this case is [[i]]. I cannot seem to get that to work in lapply.

Thank you for your help.

Upvotes: 1

Views: 1476

Answers (2)

agstudy
agstudy

Reputation: 121618

It is good to use replace for by one of the xxpply function, but better is to use vectorized functions.

Here for example , there is no need to used a for since operations are vectorized. So the first loop should be written:

AllData$Date <- 
         strptime(paste(AllData$Date, AllData$Time), "%m/%d/%y %H:%M:%S")

Same thing for the second loop:

cat(paste("Time Frame: ", names(AllData), "\n"))

EDIT In case you have a list of data.frames , you can use loop here:

  for (x in seq_along(AllData)){
       x$Date = strptime(paste(x$Date, x$Time), "%m/%d/%y %H:%M:%S")
   }

Upvotes: 5

aosmith
aosmith

Reputation: 36114

For your first loop, using lapply in conjunction with transform is useful along with an anonymous function. In this case, the x in the anonymous function refers to an element of the list (e.g., AllData[[1]]) which you can then use in transform. I found transform useful here because I can ask for variables of the list element by name.

AllData2 = lapply(AllData, function(x) transform(x, Date = strptime(paste(Date, Time), "%m/%d/%y %H:%M:%S"), 
                              Time = NULL))

I don't know where the trade function is from, so I was uncertain what you wanted to do with the second loop. If you clarify I may be able to give you an idea.

Upvotes: 2

Related Questions