Victor Maxwell
Victor Maxwell

Reputation: 314

access previous row when using apply on dataframe

I have a large data.frame which i would like to run a test on to see if each row in a particular column is equal to the previous row in that column plus some increment. The data in the column in question is of class POSIXct. I am using a for loop but this is very slow so I would like to write the code using the apply function. Here is what i have

for (i in 2:100) {
     test$test[i] <- test$date[i-1]+0.5*60*60 == test$date[i]
 }

the data.frame may be created as so

test <- 
    data.frame(date = c(seq(from = Sys.time(), length.out = 100, by = "30 min")), 
               test = c(rep(0,100))
              )

How might I translate this into an apply function?

Upvotes: 1

Views: 117

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 146239

Use diff to calculate the differences. No apply or for needed.

test$test = c(NA, as.double(diff(test$date), units = "mins") == 30)

We can convert the difftime units, so we don't need 0.5 * 60 * 60.

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 389335

You can also shift the rows and compare

test$test[2:nrow(test)] <- (test$date[1:(nrow(test) - 1)] + 0.5*60*60) == 
                            test$date[2:nrow(test)]

Upvotes: 1

Related Questions