I have data in R that looks like this:
T1 <- c(0,0,0,0,0)
T2 <- c(1,0,0,0,0)
T3 <- c(0,1,0,0,0)
T4 <- c(1,1,0,NA,1)
T5 <- c(0,1,0,NA,0)
df <- data.frame(T1,T2,T3,T4,T5)
T1 T2 T3 T4 T5
1 0 1 0 1 0
2 0 0 1 1 1
3 0 0 0 0 0
4 0 0 0 NA NA
5 0 0 0 1 0
What I am hoping to do is to turn every value after the 1st "1" appears into NA. So it would look something like this:
T1 T2 T3 T4 T5
1 0 1 NA NA NA
2 0 0 1 NA NA
3 0 0 0 0 0
4 0 0 0 NA NA
5 0 0 0 1 NA
Any suggestions? Thank you!
Using apply
from base R
Get the first 1 with which.max
first1 = which.max(x == 1)
Generate an integer that can be sequenced and subset the values that are not within the sequence.
mySeq <-ifelse(first1 == 1, length(x), first1)
Subsetted values are given NA
x[-seq(mySeq)] <- NA
return values
df[] <- t(apply(df, 1, \(x) {
first1 = which.max(x == 1)
mySeq <-ifelse(first1 == 1, length(x), first1)
x[-seq(mySeq)] <- NA
x
}))
T1 T2 T3 T4 T5
1 0 1 NA NA NA
2 0 0 1 NA NA
3 0 0 0 0 0
4 0 0 0 NA NA
5 0 0 0 1 NA