Search code examples
rdataframerowlag

Access a lagged row based on a given row in R


Let's assume my code accesses a certain row. How is it possible to manually access a lagged row. In the example my code picked the row with the date "03.01.2010". Based on this, how can I access for example the following row.

date <- c("01.01.2010","02.01.2010","03.01.2010","04.01.2010","07.01.2010")
ret <- c(1.1,1.2,1.3,1.4,1.5)

mydf <- data.frame(date, ret)
mydf

#         date ret
# 1 01.01.2010 1.1
# 2 02.01.2010 1.2
# 3 03.01.2010 1.3
# 4 04.01.2010 1.4
# 5 07.01.2010 1.5

certaindate <- "03.01.2010"

mydf[mydf$date %in% certaindate, "ret"] # this is an important line in my code and I want to keep it there!

I thought something like

mydf[mydf$date %in% certaindate +1, "ret"]

would do the trick, but it doesn't..


Solution

  • So this works:

    mydf[mydf$date %in% certaindate, "ret"] 
    # [1] 1.3
    mydf[which(mydf$date %in% certaindate)+1,]$ret
    # [1] 1.4
    

    The function which(...) returns the indices of all elements which meet the condition. Then you can add 1.

    Your code was returning a logical vector (T/F). Adding 1 to that coerces all the logical to 0 or 1, giving a numeric vector of 1 or 2, which was then used to index df.