Say I have a dataframe with the following structure:
dt dtPr id val
99 98 a 10
98 97 a 9
97 96 a 8
99 98 b 20
98 97 b 19
97 96 b 18
What is the most efficient way to create another data frame column that shows "prior value" based on the two dates? Prior value should equal the val where dtPr = dt for a given id. I could do this easily in SQL but I"m unsure about the most efficient approach in R.
Example output:
dt dtPr id val valPr
99 98 a 10 9
98 97 a 9 8
97 96 a 8 NULL
99 98 b 20 19
98 97 b 19 18
97 96 b 18 NULL
Code to generate sample data frame:
a <- c(99,98,97,99,98,97)
b <- c(98,97,96,98,97,96)
c <- c("a","a","a","b","b","b")
d <- c(10,9,8,20,19,18)
e <- data.frame(dt = a, dtPr = b, id = c, val = d)