如何将inf与橄榄酸和dplyr case_当
我想构建一个自定义功能,该功能返回X年前的日期,或者在X提供的情况下是无限的,将恢复到一个特殊的日期。我正在使用dplyr
和lubridate
。这是一个微不足道的示例:
foo <- function(years_ago) {
case_when(
years_ago == Inf ~ as.Date("1800-01-01"),
TRUE ~ Sys.Date() - years(years_ago)
)
}
foo(1)
正式返回1年前的日期。但是,foo(inf)
给我错误: 参数无法解释为逻辑
。即使在满足第一个条件时,似乎R跳跃以评估Case_时的真实行。
有什么办法可以使这些整理功能效果很好,还是需要在基本r中找到解决方法?
I want to build a custom function which returns a date x years ago, or in the case the x supplied is infinite, reverts to a special date. I'm using dplyr
and lubridate
. Here is a trivial example:
foo <- function(years_ago) {
case_when(
years_ago == Inf ~ as.Date("1800-01-01"),
TRUE ~ Sys.Date() - years(years_ago)
)
}
foo(1)
duly returns the date 1 year ago. However, foo(Inf)
gives me the error:argument is not interpretable as logical
. It seems that R jumps to evaluate the TRUE line of the case_when statement, even when the first condition is met.
Is there any way I can get these tidyverse functions to play nicely, or do I need to find a workaround in base R?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是一个漂亮的解决方案,但我认为这有效吗?不确定为什么在
IS.Infinite
case_when 中对Inf
进行测试也失败了,因为这是我的第一个想法。另外,给定上述已经作为“如果”的一部分进行了逻辑语句,那么以下内容也应该起作用?
It's not a pretty solution, but I think this works? Not sure why testing for
Inf
withis.infinite
within thecase_when
also fails though as that was my first thought.Alternatively, given the above already carries out the logical statement as part of the "if", then the following should also work?
case_when
始终评估这两个条件。因此,尽管假设您的价值为inf
,但何时无法评估第二行,它实际上是直观的。然后问题是年
函数无法处理无限的值。您可以在case_时可以做的事情,就是添加一个ifelse命令,该命令确保年份函数仅在不是无限的值上运行。
一些例子:
case_when
always evaluates both conditions. So while it would be intuitive to assume that if your value isInf
, the case when would not evaluate the second line, it actually does. And then the problem is that theyears
function can't handle infinite values.What you could do in the case_when, is to simply add an ifelse command that makes sure the years function is only run on values that are not infinite.
Some examples: