0

here is an example of my data:

m <- data.frame(swim = c(0,1,0,0), time1 = c(1,2,3,4), time2 = c(2,3,4,5))

I want to replace all numbers in columns time1 and time2 with NA after the row where there is a 1 in m$swim. It should look like this:

n <- data.frame(swim = c(0,1,0,0), time1 = c(1,2,NA,NA), time2 = c(2,3,NA,NA))

Thank you!
NorthLattitude
  • 201
  • 1
  • 12

3 Answers3

1

In dplyr you can do :

library(dplyr)
m %>%
  mutate(across(starts_with('time'), 
           ~replace(., row_number() > match(1, swim), NA)))

A base R option however, would be more efficient.

cols <- grep('time', names(m))
inds <- match(1, m$swim)
m[(inds + 1):nrow(m), cols] <- NA
m
#  swim time1 time2
#1    0     1     2
#2    1     2     3
#3    0    NA    NA
#4    0    NA    NA
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

A base R solution would be:

#Data
m <- data.frame(swim = c(0,1,0,0), time1 = c(1,2,3,4), time2 = c(2,3,4,5))
#Detect position
index <- min(which(m$swim==1)) 
#Replace
m[(index+1):dim(m)[1],-1] <- NA

Output:

  swim time1 time2
1    0     1     2
2    1     2     3
3    0    NA    NA
4    0    NA    NA
Duck
  • 39,058
  • 13
  • 42
  • 84
0

Using data.table, the result would be as follows:

library(data.table)
setDT(m)

#Start after the row with the 1
stop.here <- which(m$swim == 1)+1

these_rows <- seq(stop.here,length(m$swim),1)

m <- m[these_rows,time1:=NA]
m <- m[these_rows,time2:=NA]