A. *_*tam 5 r date posixct lubridate dplyr
我在R中遇到了一些非常特殊的行为。我认为这甚至可能是一个错误,但是我想在这里检查是否有人熟悉它或知道解决方案。
我要尝试的操作如下:我有一个数据框,其中的日期分配给了组。我正在对这些组执行循环,在其中计算该组中日期的最大值。next如果此最大日期为,我想跳过循环()的其余部分NA。但是,这不会正确发生。
考虑以下代码:
library(dplyr)
library(lubridate)
a <- data.frame(group = c(1,1,1,1,1, 2,2,2,2, 3),
ds = as_datetime(dmy('01-01-2018', NA, '03-01-2018', NA, '05-01-2018',
'02-01-2018', '04-01-2018', '06-01-2018', '08-01-2018',
NA)))
for (i in 1:3) {
max_ds <- a %>% filter(group == i) %>% .$ds %>% max(na.rm = T)
if (is.na(max_ds)) { next }
print(max_ds)
}
Run Code Online (Sandbox Code Playgroud)
预期的输出是:
# [1] "2018-01-05 UTC"
# [1] "2018-01-08 UTC"
Run Code Online (Sandbox Code Playgroud)
但是,获得的输出是:
# [1] "2018-01-05 UTC"
# [1] "2018-01-08 UTC"
# [1] NA
Run Code Online (Sandbox Code Playgroud)
该谜题的症结似乎在于该na.rm条款。如果将其删除,则会发生以下情况:
for (i in 1:nr_groups) {
max_ds <- a %>% filter(group == i) %>% .$ds %>% max()
if (is.na(max_ds)) { next }
print(max_ds)
}
# [1] "2018-01-08 UTC"
Run Code Online (Sandbox Code Playgroud)
这正是预期的结果。
有任何想法吗?
问题是你NA与na.rm = TRUE. 然后发生这种情况:
max(NA, na.rm = TRUE)
#[1] -Inf
#Warning message:
#In max(NA, na.rm = TRUE) : no non-missing arguments to max; returning -Inf
Run Code Online (Sandbox Code Playgroud)
结果显然不是NA。如果您传递一个日期时间变量,结果仍然不是NA,而是打印为NA:
max(as.POSIXct(NA), na.rm = TRUE)
#[1] NA
#Warning message:
#In max.default(NA_real_, na.rm = TRUE) :
# no non-missing arguments to max; returning -Inf
as.POSIXct(-Inf, origin = "1900-01-01")
#[1] NA
unclass(as.POSIXct(-Inf, origin = "1900-01-01"))
#[1] -Inf
#attr(,"tzone")
#[1] ""
Run Code Online (Sandbox Code Playgroud)
您可能想测试is.finite:
!is.finite(max(as.POSIXct(NA), na.rm = TRUE))
#[1] TRUE
#Warning message:
#In max.default(NA_real_, na.rm = TRUE) :
# no non-missing arguments to max; returning -Inf
Run Code Online (Sandbox Code Playgroud)