我有一个数据框如下所示,我在lse
列中比较连续值。如果lse 0
的值后跟1
,我想将END_DATE
lse
的{{1}}值设为0
NA
输入:
END_DATE lse
2016-01-20 0
2015-08-16 1
预期产出:
END_DATE lse
NA 0
2015-08-16 1
我已经尝试过以下代码,但它无法正常工作而且没有任何错误。
for (i in length(loan_test1$lse)){
if (length(loan_test1$lse) == 0 & length(loan_test1$lse)+1 == 1) {
loan_test1$END_DATE[i] <- "NA"
}
}
任何人都可以帮助我吗?
答案 0 :(得分:1)
library(lubridate)
library(tidyverse)
df <- data.frame(END_DATE = seq.Date(from = (today()-99),to = today(),by=1),lse = sample(c(0,1), 100, replace = TRUE))
df <- df %>% mutate(leadlse = lead(lse))
condition <- df$lse == 0 & df$leadlse ==1
df$END_DATE[condition] = NA
df <- df %>% select(-leadlse)
df
或更简单:
df <- data.frame(END_DATE = seq.Date(from = (today()-99),to = today(),by=1),lse = sample(c(0,1), 100, replace = TRUE))
df$END_DATE[(df$lse == 0 & lead(df$lse) == 1)] <- NA