I am completely new at R. How can I sum-up value and create another row based on a condition. Example:
a b c d
0 a 1 100
0 a 2 300
0 b 3 150
0 b 4 250
after the manipulation, I would get another row that would look like this
a b c d new_row
0 a 1 100 100
0 a 2 300 400
0 b 3 150 250
0 b 4 250 0
So basically if the b=="a" sum up values in d to make a new_row. but if its b, subtract them.
df<- mutate(df, D = lag(d) D)
But it says I can't take values from the D column yet. and pointers to a totally noob programmer in R?
CodePudding user response:
You could use cumsum
combined with ifelse
library(dplyr)
df %>%
mutate(new_col = cumsum(ifelse(b == "b", -d, d)))
to get
# A tibble: 4 x 5
a b c d new_col
<dbl> <chr> <dbl> <dbl> <dbl>
1 0 a 1 100 100
2 0 a 2 300 400
3 0 b 3 150 250
4 0 b 4 250 0