DJ-AFC
DJ-AFC

Reputation: 569

Add row value to previous row value in R

I have a very basic question as I am relatively new to R. I was wondering how to add a value in a column to the previous value and repeat right down a column of 1000s of values? Note, I do not want a cumulative sum and therefore the cumsum function is of no use. Say my column is called WD, I want to add WD1 to WD2, WD2 to WD3, WD3 to WD4 etc. all the way down and output these sums as a new column. Is there an easy way? Many thanks.

A reproducible example:

set.seed(111)
df1 <- data.frame(WD=sample(10))

#result
df1
   WD new
1   6   6
2   7  13
3   3  10
4   4   7
5   8  12
6  10  18
7   1  11
8   2   3
9   9  11
10  5  14

Upvotes: 5

Views: 9183

Answers (2)

Steven Beaupr&#233;
Steven Beaupr&#233;

Reputation: 21621

Another option, using lag() from dplyr:

library(dplyr)
mutate(df1, new = WD + lag(WD, default = 0))

Or using shift() from data.table:

library(data.table)
setDT(df1)[, new := WD + shift(WD, fill = 0)]

Note: The default type of shift() is "lag". The other possible value is "lead".

Which gives:

#   WD new
#1   6   6
#2   7  13
#3   3  10
#4   4   7
#5   8  12
#6  10  18
#7   1  11
#8   2   3
#9   9  11
#10  5  14

Upvotes: 3

akrun
akrun

Reputation: 887008

We add the current row (WD[-nrow(df1)]) with the next row (WD[-1L]) and concatenate with the first element to create the column.

df1$newColumn <- with(df1, c(WD[1],WD[-1]+WD[-nrow(df1)]))

Upvotes: 3

Related Questions