这是我的数据示例:
m <- data.frame(swim = c(0,1,0,0), time1 = c(1,2,3,4), time2 = c(2,3,4,5))
我想在NA
中有1
的行之后,用m$swim
替换time1和time2列中的所有数字。它应该看起来像这样:
n <- data.frame(swim = c(0,1,0,0), time1 = c(1,2,NA,NA), time2 = c(2,3,NA,NA))
Thank you!
答案 0 :(得分:1)
在dplyr
中,您可以执行以下操作:
library(dplyr)
m %>%
mutate(across(starts_with('time'),
~replace(., row_number() > match(1, swim), NA)))
但是,基本的R选项会更有效。
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
答案 1 :(得分:1)
base R
解决方案是:
#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
输出:
swim time1 time2
1 0 1 2
2 1 2 3
3 0 NA NA
4 0 NA NA
答案 2 :(得分:0)
使用data.table,结果如下:
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]