我试图了解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
是可以包含日期或为空的字符串)。
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
或effective_to
的长度小于1,那么它将不执行后续步骤。我想在第一行中,由于effective_from
为空,因此我上面的语句在尝试评估str_length('effective_from')
时将返回FALSE,从而使进一步的评估短路。
不确定为什么它不起作用...我将如何实现以元素或AND或OR短路的方式?
答案 0 :(得分:2)
这是基本的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