samedi 25 avril 2020

Assigning NAs to rows with conditional statement in r

I'm trying to assign NAs to the first two rows of each event, with the following conditional statement: If the first day of each event has a value of "variable" = 0, check the day before. If the day before (last day of previous event) has a "variable" > 0, then assign NAs to the first two rows of the event having "variable" = 0 on the first day. If the day before has a "variable" = 0, do nothing.

Here is an example:

day <- c(1:16)
event<- c(1,1,2,3,4,4,4,5,5,5,6,6,6,7,7,7)
variable<- c(0,0,5,0,0,0,10,0,1,1,0,0,0,0,0,0)
A<- data.frame(day, event, variable)
     day  event  variable
1     1     1        0
2     2     1        0
3     3     2        5
4     4     3        0
5     5     4        0
6     6     4        0
7     7     4       10
8     8     5        0
9     9     5        1
10   10     5        1
11   11     6        0
12   12     6        0
13   13     6        0
14   14     7        0
15   15     7        0
16   16     7        0

And how it should look like

     day  event  variable
1     1     1        0
2     2     1        0
3     3     2        5
4     4     3       NA
5     5     4        0
6     6     4        0
7     7     4       10
8     8     5       NA
9     9     5       NA
10   10     5        1
11   11     6       NA
12   12     6       NA
13   13     6        0
14   14     7        0
15   15     7        0
16   16     7        0

Note: It doesn't matter if event 1 has to be assigned with NAs I tried to do this with if conditions, but is not working well. Any idea? and thanks in advance!

Aucun commentaire:

Enregistrer un commentaire