我试图在to
变量中添加一天,但前提是from
没有丢失:
df <- data.frame(from = c("2020-01-01", "2020-02-01", ""),
to = c("2020-01-05", "2020-02-20", "2020-03-04"))
df <- df %>% mutate(
from = as.Date(from),
to = as.Date(to),
to = ifelse(!is.na(from), to + 1, to)
)
df
显然,这不起作用:(.有人能告诉我怎么做吗?
试试这个。函数ifelse()
用于将日期转换为数字。相反,您可以使用dplyr
中的if_else()
。这里的代码:
#Data
df <- data.frame(from = c("2020-01-01", "2020-02-01", ""),
to = c("2020-01-05", "2020-02-20", "2020-03-04"))
#Variables
df <- df %>% mutate(
from = as.Date(from),
to = as.Date(to),
to = if_else(!is.na(from), to + 1, to)
)
#Output
df
输出:
df
from to
1 2020-01-01 2020-01-06
2 2020-02-01 2020-02-21
3 <NA> 2020-03-04
我们也可以进行
library(lubridate)
library(dplyr)
df %>%
mutate(across(everything(), ymd),
to = case_when(!is.na(from)~ to+1, TRUE ~ to))
-输出
# from to
#1 2020-01-01 2020-01-06
#2 2020-02-01 2020-02-21
#3 <NA> 2020-03-04