如何防止ifelse()将Date对象转换成数字对象 [英] How to prevent ifelse() from turning Date objects into numeric objects
问题描述
我使用函数 ifelse()
来操纵日期向量。我预计结果是类 Date
,并且惊奇地得到一个数字
矢量。这是一个例子:
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
vector?如果是这样,什么功能?如果没有,如何强制 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.
推荐答案
您可以使用 dplyr :: if_else
。
从 dplyr 0.5.0
发行说明:[ if_else
]具有更严格的语义, ifelse() code>:
true
和 false
参数必须是相同的类型,这使得不太令人惊讶的返回类型,并保留S3矢量,如日期。
From dplyr 0.5.0
release notes: "[if_else
] have stricter semantics that ifelse()
: the true
and false
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屋!