如何防止 ifelse() 将 Date 对象转换为数字对象 [英] How to prevent ifelse() from turning Date objects into numeric objects
问题描述
我正在使用函数 ifelse()
来操作日期向量.我希望结果是 Date
类,结果却意外地得到了一个 numeric
向量.下面是一个例子:
I am using the function ifelse()
to manipulate a date vector. I expected the result to be of class Date
, and was surprised to get a numeric
vector instead. Here is an example:
dates <- as.Date(c('2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04', '2011-01-05'))
dates <- ifelse(dates == '2011-01-01', dates - 1, dates)
str(dates)
这尤其令人惊讶,因为对整个向量执行操作返回一个 Date
对象.
This is especially surprising because performing the operation across the entire vector returns a Date
object.
dates <- as.Date(c('2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04','2011-01-05'))
dates <- dates - 1
str(dates)
我应该使用其他函数来操作 Date
向量吗?如果有,是什么功能?如果没有,我如何强制 ifelse
返回与输入相同类型的向量?
Should I be using some other function to operate on Date
vectors? If so, what function? If not, how do I force ifelse
to return a vector of the same type as the input?
ifelse
的帮助页面表明这是一项功能,而不是错误,但我仍在努力寻找对我发现的令人惊讶的行为的解释.
The help page for ifelse
indicates that this is a feature, not a bug, but I'm still struggling to find an explanation for what I found to be surprising behavior.
推荐答案
您可以使用 data.table::fifelse
(data.table >= 1.12.3
) 或 dplyr::if_else
.
You may use data.table::fifelse
(data.table >= 1.12.3
) or dplyr::if_else
.
与 ifelse
不同,felse
保留输入的类型和类别.
Unlike
ifelse
,fifelse
preserves the type and class of the inputs.
library(data.table)
dates <- fifelse(dates == '2011-01-01', dates - 1, dates)
str(dates)
# Date[1:5], format: "2010-12-31" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05"
dplyr::if_else
来自 dplyr 0.5.0
发行说明:
[if_else
] 具有比 ifelse()
更严格的语义:true
和 false
参数必须是同类型.这提供了一个不那么令人惊讶的返回类型,并保留了像 dates" 这样的 S3 向量..
[
if_else
] have stricter semantics thatifelse()
: thetrue
andfalse
arguments must be the same type. This gives a less surprising return type, and preserves S3 vectors like dates" .
library(dplyr)
dates <- if_else(dates == '2011-01-01', dates - 1, dates)
str(dates)
# Date[1:5], format: "2010-12-31" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05"
这篇关于如何防止 ifelse() 将 Date 对象转换为数字对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!