How to use R do this coding? I have a dataframe which containes two columns "data" and "dataSums". The values of these two columnes are as follow. You can see the picture of the dataframe.
The explaination is as below.
If the value in the first column "data" is 1 , then the value in the second column "dataSum" is the sum of all the row till now in the first column.
That is
If row 1 of "data" is 1 , then row 1 of "dataSum" is 1.
If row 2 of "data" is 1 , then row 2 of "dataSum" is 1 1=2.
If row 3 of "data" is 1 , then row 3 of "dataSum" is 1 1 1=3.
If row 5 of "data" is 1 , then row 3 of "dataSum" is 1 1 1 0 1=4.
If row 7 of "data" is 1 , then row 3 of "dataSum" is 1 1 1 0 1 0 1=5.
If the value in the first column "data" is 0 , then the value in the second column "dataSum" is 0.
How to use R do this coding? Many thanks!
CodePudding user response:
This is it:
dataSum <- cumsum(data)
dataSum[data == 0] <- 0
CodePudding user response:
In addition to @WhatIf solution, you could also do the following ways, assuming your data is df
library(dplyr)
mutate(df, dataSum=if_else(data==1, cumsum(data),0))
library(data.table)
setDT(df)[, dataSum:=fifelse(data==1, cumsum(data),0)]
Output:
data dataSum
<num> <num>
1: 1 1
2: 1 2
3: 1 3
4: 0 0
5: 1 4
6: 0 0
7: 1 5