user3408139
user3408139

Reputation: 197

subtract from first row in a data.table in R

I have the following table and I need to the output as shown. Basically, subtract the value in first row of "num_date" column from 2nd row, 3rd row, 4th row etc.

Table1:

Year    num_date
2016    16703
2016    16705
2016    16706
2016    16708
.
.

Output:

Year    num_date
2016    0
2016    2
2016    3
2016    5

Can somebody help me to achieve this in R?

Thanks in advance,

Upvotes: 2

Views: 1188

Answers (1)

akuiper
akuiper

Reputation: 214957

You can do this by extracting the first value with indexing [1], subtract it from the column, then assign it back:

df$num_date = df$num_date - df$num_date[1]

df$num_date = df$num_date - df$num_date[1]
df
#  Year num_date
#1 2016        0
#2 2016        2
#3 2016        3
#4 2016        5

Upvotes: 1

Related Questions