Reputation: 211
Is there a way to refer to the previous row in apply
's in R?
For example, my data.frame
is sorted in the order of dates, and I want to find the differences between the date in the previous row and current row. This is easy in a loop.
for( i in 2:nrow(Y)) {
Y[i,]$window = as.numeric(as.Date( Y[i, ]$start_date ) -
as.Date( Y[i-1, ]$end_date ))
}
Can I do this using apply?
Upvotes: 3
Views: 1826
Reputation: 115382
Try using head
(or tail
)
Y$window <- as.numeric(c(NA, as.Date(tail(y$start.date,-1)) - as.Date(head(y$end.date,-1)) ))
Upvotes: 1