I have a dataset like below with columns of 1s and 0s. I would like to add a final column that identifies the column name of the final occurrence of 0 per row.
have = data.frame(a = c(1,0,1,1,0,0,1,1,1,0),
b = c(1,0,1,1,1,0,1,1,0,0),
c = c(0,0,0,1,0,1,1,1,1,0),
d = c(1,0,1,1,0,0,0,1,0,1),
e = c(1,1,1,1,1,1,1,1,1,1))
> have
a b c d e
1 1 1 0 1 1
2 0 0 0 0 1
3 1 1 0 1 1
4 1 1 1 1 1
5 0 1 0 0 1
6 0 0 1 0 1
7 1 1 1 0 1
8 1 1 1 1 1
9 1 0 1 0 1
10 0 0 0 1 1
I would like the output to look like this where the final column specifies the column name of the last occurring 0 and if one does not exist return NA.
> want
a b c d e last_0
1 1 1 0 1 1 c
2 0 0 0 0 1 d
3 1 1 0 1 1 c
4 1 1 1 1 1 <NA>
5 0 1 0 0 1 d
6 0 0 1 0 1 d
7 1 1 1 0 1 d
8 1 1 1 1 1 <NA>
9 1 0 1 0 1 d
10 0 0 0 1 1 c
I've tried using max.col but it returns the last column name if a zero does not exist. Any other solutions? A dplyr solution is preferred.
> have$last_0 = names(have)[max.col(have == 0, ties.method = "last")]
> have
a b c d e last_0
1 1 1 0 1 1 c
2 0 0 0 0 1 d
3 1 1 0 1 1 c
4 1 1 1 1 1 e
5 0 1 0 0 1 d
6 0 0 1 0 1 d
7 1 1 1 0 1 d
8 1 1 1 1 1 e
9 1 0 1 0 1 d
10 0 0 0 1 1 c