0
votes

I'm at a loss to cycle through a data frame and calculate a variable that is a function of different/multiple rows. Please see the following data as an example.

date	var1	var2	var3
12/29/2013	10	34	0
12/30/2013	10	34	15
12/31/2013	8	27	15
1/1/2014	8	27	0
1/2/2014	2	7	10
1/3/2014	10	35	20
1/4/2014	13	45	10

I would like to create a variable that is a function of the current row and the next row. For example,

var4(12/31/2013) = var1(12/31/2013) + var2(1/1/2014) + var3(12/31/2013)

For the last element in the dataframe, there is no (n+1) variable, so I'd like to assign a missing value/exception value in that case. Any guidance you could provide would be wonderful. Thank you in advance!

1
just shift the vector var2 one element back: your.dataframe$var4 <- with(your.dataframe, var1 + var3 + c(var2[-1],NA)) - Marat Talipov
@MaratTalipov - that's a really good answer. You should post it - Rich Scriven
This worked like a charm. Thank you! - formerfoodie

1 Answers

3
votes

you could try

 library(dplyr)
 df %>%
     mutate(var4=var1+lead(var2)+var3)