mutate
函数时,日期列会变成双列!
示例:
df
## my_date_01 my_date_02
## <date> <date>
## 1 2018-09-13 NA
## 2 NA 2018-12-09
## 3 NA 2018-12-16
## 4 NA 2019-01-19
## 5 NA 2018-11-19
## 6 NA 2018-12-16
## 7 NA 2018-08-08
## 8 NA 2018-10-24
## 9 2019-03-26 NA
##10 NA 2018-12-11
df %>% mutate(my_date_01 = ifelse(my_date_01 > lubridate::date("2019-01-01"),
NA,
my_date_01))
## my_date_01 my_date_02
## <dbl> <date>
## 1 17787 NA
## 2 NA 2018-12-09
## 3 NA 2018-12-16
## 4 NA 2019-01-19
## 5 NA 2018-11-19
## 6 NA 2018-12-16
## 7 NA 2018-08-08
## 8 NA 2018-10-24
## 9 NA NA
##10 NA 2018-12-11
在这里发生了两次事情:
确实被所需的日期替换为
NA
整列正在转换为双重(这是错误的)
as.Date(NA)
上面的修复程序可能仍然无法使用
ifelse
ifelse
...
ans <- test # assigned to logical vector test
len <- length(ans)
ypos <- which(test)
npos <- which(!test)
if (length(ypos) > 0L)
ans[ypos] <- rep(yes, length.out = len)[ypos]
if (length(npos) > 0L)
ans[npos] <- rep(no, length.out = len)[npos]
ans
}
它可以使用以下代码,因为在完成分配的同时将逻辑向量胁迫到数字,而该分配不会在上面的
ans <- as.Date(rep(NA, length(test)))
步骤上进行。
as.Date
data
df %>%
mutate(my_date_01 = ifelsenew(my_date_01 > lubridate::date("2019-01-01"),
as.Date(NA),
my_date_01))
当在
df <- structure(list(my_date_01 = structure(c(17787, NA, NA, NA, NA,
NA, NA, NA, 17981, NA), class = "Date"), my_date_02 = structure(c(NA,
17874, 17881, 17915, 17854, 17881, 17751, 17828, NA, 17876), class = "Date")),
row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"), class = "data.frame")
语句中使用
ifelse
mutate
。至少,如果涉及日期列,这是正确的。然后,您的代码正常工作: