Home > Software engineering >  Create a new variable that is the summation from the first value
Create a new variable that is the summation from the first value

Time:12-06

This is something that should be simple but I can't figure it out. I have a variable var and need to create another variable var2 that is calculated adding the value of var from the first observation. The problem is that the value of var2 at the first observation (a) should be 14, not 28. I tried a solution using the function first but it didn't work out and that's because everything is added to 14, even the first observation.

CODE:

library(dplyr)

data_a <- read.csv(text = "
obs,var
a, 14
b, 124
c, 180
d, 40
e, 20
") 

data_b <- data_a %>%
  mutate(var2 = first(var)   var)

OUTPUT:

enter image description here

The expected result should have a value of 14 for var2 at observation a.

CodePudding user response:

Check if row_number is bigger than 1, then update:

data_a %>%
  mutate(var2 = ifelse(row_number() > 1, first(var)   var, var))
#   obs var var2
# 1   a  14   14
# 2   b 124  138
# 3   c 180  194
# 4   d  40   54
# 5   e  20   34
  • Related