如何防止 ifelse() 将 Date 对象转换为数字对象
我正在使用函数 ifelse()
来操作日期向量。我预计结果是 Date
类,但很惊讶地得到了 numeric
向量。这是一个示例:
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
对象。
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
返回与输入相同类型的向量?
ifelse 的帮助页面表明这是一个功能,而不是一个错误,但我仍在努力寻找对我发现的令人惊讶的行为的解释。
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)
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)
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?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用
data.table::fifelse
(data.table >= 1.12.3
) 或dplyr::if_else
。data.table::fifelse
dplyr::if_else
来自
dplyr 0.5.0
发行说明:You may use
data.table::fifelse
(data.table >= 1.12.3
) ordplyr::if_else
.data.table::fifelse
dplyr::if_else
From
dplyr 0.5.0
release notes:它与
ifelse
的记录Value相关:归结为它的含义,
ifelse
使因子失去其级别,日期失去其类别,并且仅恢复其模式(“数字”)。试试这个:你可以创建一个
safe.ifelse
:稍后的注释:我看到 Hadley 在 magrittr/dplyr/tidyr 数据复合体中构建了一个
if_else
-塑造确实保留结果类的包。It relates to the documented Value of
ifelse
:Boiled down to its implications,
ifelse
makes factors lose their levels and Dates lose their class and only their mode ("numeric") is restored. Try this instead:You could create a
safe.ifelse
:A later note: I see that Hadley has built an
if_else
into the the magrittr/dplyr/tidyr complex of data-shaping packages that does preserve the class of the consequent.DWin 的解释很到位。在我意识到我可以简单地在 ifelse 语句之后强行强制上课之前,我摆弄并与之斗争了一段时间:
起初,这对我来说有点“hackish”。但现在我只是认为这是为我从 ifelse() 获得的性能回报付出的一个小小的代价。而且它仍然比循环简洁得多。
DWin's explanation is spot on. I fiddled and fought with this for a while before I realized I could simply force the class after the ifelse statement:
At first this felt a little "hackish" to me. But now I just think of it as a small price to pay for the performance returns that I get from ifelse(). Plus it's still a lot more concise than a loop.
这不起作用的原因是 ifelse() 函数将值转换为因子。一个很好的解决方法是在评估之前将其转换为字符。
除了基础 R 之外,这不需要任何库。
The reason why this won't work is because, ifelse() function converts the values to factors. A nice workaround would be to convert it to characters before evaluating it.
This wouldn't require any library apart from base R.
建议的方法不适用于因子列。我想建议这种改进:
顺便说一句:ifelse很糟糕...能力越大,责任越大,即1x1矩阵和/或数字的类型转换[例如,当它们应该被添加时]对我来说没问题,但这种类型转换ifelse 显然是不需要的。我现在多次遇到 ifelse 的同一个“错误”,它只是不断地窃取我的时间:-(
FW
The suggested method does not work with factor columns. Id like to suggest this improvement:
By the way: ifelse sucks... with great power comes great responsibility, i.e. type conversions of 1x1 matrices and/or numerics [when they should be added for example] is ok to me but this type conversion in ifelse is clearly unwanted. I bumped into the very same 'bug' of ifelse multiple times now and it just keeps on stealing my time :-(
FW
@fabian-werner 提供的答案很好,但是对象可以有多个类,并且“factor”不一定是
class(yes)
返回的第一个类,所以我建议这个小修改检查所有类属性:我还向 R 开发团队提交了请求,要求添加一个记录选项,以便让 base::ifelse() 根据用户选择要保留的属性来保留属性。请求位于:https://bugs.r-project.org/ bugzilla/show_bug.cgi?id=16609 - 它已经被标记为“WONTFIX”,因为它一直都是现在的样子,但我提供了一个后续论点为什么简单的添加可以让很多 R 用户省去麻烦。也许您在该错误线程中的“+1”会鼓励 R Core 团队重新审视。
编辑:这是一个更好的版本,允许用户指定要保留的属性,“cond”(默认 ifelse() 行为)、“yes”(按照上面代码的行为)或“no”(对于以下情况) “no”值的属性更好:
The answer provided by @fabian-werner is great, but objects can have multiple classes, and "factor" may not necessarily be the first one returned by
class(yes)
, so I suggest this small modification to check all class attributes:I have also submitted a request with the R Development team to add a documented option to have base::ifelse() preserve attributes based on user selection of which attributes to preserve. The request is here: https://bugs.r-project.org/bugzilla/show_bug.cgi?id=16609 - It has already been flagged as "WONTFIX" on the grounds that it has always been the way it is now, but I have provided a follow-up argument on why a simple addition might save a lot of R users headaches. Perhaps your "+1" in that bug thread will encourage the R Core team to take a second look.
EDIT: Here's a better version that allows the user to specify which attributes to preserve, either "cond" (default ifelse() behaviour), "yes", the behaviour as per the code above, or "no", for cases where the attributes of the "no" value are better:
为什么不在这里使用索引呢?
Why not use indexing here?