这很奇怪:R ifelse()似乎做了一些(不需要的)转换:假设我有一个时间戳矢量(可能是NA),NA值应该与现有日期区别对待,例如,只是忽略:
formatString = "%Y-%m-%d %H:%M:%OS"
timestamp = c(as.POSIXct(strptime("2000-01-01 12:00:00.000000", formatString)) + (1:3)*30, NA)
Run Code Online (Sandbox Code Playgroud)
现在
timestamp
#[1] "2000-01-01 12:00:30 CET" "2000-01-01 12:01:00 CET" "2000-01-01 12:01:30 CET"
#[6] NA
Run Code Online (Sandbox Code Playgroud)
根据需要,但翻译30秒会导致
ifelse(is.na(timestamp), NA, timestamp+30)
#[1] 946724460 946724490 946724520 NA
Run Code Online (Sandbox Code Playgroud)
请注意,仍然timestamp+30按预期工作,但我想说我想用固定日期替换NA日期,并将所有其他日期翻译30秒:
fixedDate = as.POSIXct(strptime("2000-01-01 12:00:00.000000", formatString))
ifelse(is.na(timestamp), fixedDate, timestamp+30)
#[1] 946724460 946724490 946724520 946724400
Run Code Online (Sandbox Code Playgroud)
问题:这个解决方案有什么问题,为什么它没有按预期工作?
编辑:所需的输出是30秒转换的时间戳(不是整数)的向量,NA被替换为...
如果您看一下ifelse编写方式,它的一段代码如下所示:
ans <- test
ok <- !(nas <- is.na(test))
if (any(test[ok]))
ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok]
Run Code Online (Sandbox Code Playgroud)
请注意,答案从逻辑上开始,与测试相同。然后,已将元素test == TRUE分配给的值yes。
然后,这里的问题是将一个逻辑向量的一个或多个元素分配为POSIX.ct类的日期会发生什么。您可以查看执行以下操作会发生什么:
x <- c(TRUE, FALSE)
class(x)
# logical
x[1] <- Sys.time()
class(x)
# numeric
Run Code Online (Sandbox Code Playgroud)
您可以通过编写以下内容解决此问题:
timestamp <- timestamp + 30
timestamp[is.na(timestamp)] <- fixedDate
Run Code Online (Sandbox Code Playgroud)
您也可以这样做:
fixedDate = as.POSIXct(strptime("2000-01-01 12:00:00.000000", formatString))
unlist(ifelse(is.na(timestamp), as.list(fixedDate), as.list(timestamp+30)))
Run Code Online (Sandbox Code Playgroud)
这利用了替换操作员[<-在右侧处理列表的方式。
您也可以像这样重新添加class属性:
x <- ifelse(is.na(timestamp), fixedDate, timestamp+30)
class(x) <- c("POSIXct", "POSIXt")
Run Code Online (Sandbox Code Playgroud)
或者,如果您迫不及待地想像这样一行:
`class<-`(ifelse(is.na(timestamp), fixedDate, timestamp+30), c("POSIXct", "POSIXt"))
Run Code Online (Sandbox Code Playgroud)
或复制以下属性fixedDate:
x <- ifelse(is.na(timestamp), fixedDate, timestamp+30)
attributes(x) <- attributes(fixedDate)
Run Code Online (Sandbox Code Playgroud)
最后一个版本的优点是也可以复制tzone属性。
从dplyr 0.5.0开始,您还可以使用dplyr::if_elsewhich在输出中保留类,并为true和false参数强制执行相同的类。