我试图了解在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)但我说错了:
charToDate(x)错误:字符串不是标准的、明确的格式
在运行上面的语句而不是错误之后,我期望得到:FALSE, FALSE, FALSE, TRUE。
我认为如果effective_from或effective_to的长度小于1,那么它就不会执行后续步骤。在第一行中,我可以想象,由于effective_from是空白的,所以在试图计算str_length('effective_from')时,上面的语句将返回FALSE,从而短路了进一步的计算。
不知道为什么不管用..。我将如何实现短路元素-明智和或OR?
发布于 2020-01-13 20:39:25
下面是一个基本的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 TRUEhttps://stackoverflow.com/questions/59723419
复制相似问题