我试图了解如何在R中实现短路。这是一个示例data.frame:
v <- data.frame(id=c(1,2,3,4), effective_from=c('', '1/1/2001', '10/1/2001', '1/1/2002'), effective_to=c('', '1/10/2001', '', '1/1/2001'))
id effective_from effective_to
1 1
2 2 1/1/2001 1/10/2001
3 3 10/1/2001
4 4 1/1/2002 1/1/2001
我认为以下语句将起作用(假设effective_from
并且effective_to
是可能包含Date或为空的字符串)。
str_length(v$effective_from) > 0 & str_length(v$effective_to) > 0 & as.Date(v$effective_from) > as.Date(v$effective_to)
但是我收到一个错误消息:
Error in charToDate(x) : character string is not in a standard unambiguous format
我期望得到:FALSE, FALSE, FALSE, TRUE
在运行上面的语句而不是错误之后。
我会认为,如果effective_from
or的长度effective_to
小于1,那么它将不会执行后续步骤。我想在第一行中,由于effective_from
为空,因此我上面的陈述在尝试评估时将返回FALSE,str_length('effective_from')
从而使进一步的评估短路。
不知道为什么它不起作用...我将如何实现短路的AND或OR运算?
这是基本的R解决方案,其中使用nchar()
+ as.vector()
+ as.Date()
:
res <- with(v, nchar(as.vector(effective_from)) >0
& nchar(as.vector(effective_to))>0
& as.Date(as.vector(effective_from), "%m/%d/%Y") > as.Date(as.vector(effective_to), "%m/%d/%Y"))
这样
> res
[1] FALSE FALSE FALSE TRUE
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句