我有一个 ifelse 条件,我想从 lubridate 包返回一个 years
值。
但是,它确实在 ifelse 中返回 0,我不知道为什么。
library(lubridate)
years(1)
[1] "1y 0m 0d 0H 0M 0S" # correct
years(2)
[1] "2y 0m 0d 0H 0M 0S" # correct
ifelse(1 == 1, years(1), years(2))
[1] 0 # wrong
谁能解释为什么 ifelse 返回 0?
最佳答案
这就是它发生的原因。这是来自 ifelse
源代码的底部,它将在您的示例中运行。
ans <- test
len <- length(ans)
ypos <- which(test)
npos <- which(!test)
if (length(ypos) > 0L)
ans[ypos] <- rep(yes, length.out = len)[ypos]
if (length(npos) > 0L)
ans[npos] <- rep(no, length.out = len)[npos]
ans
该函数正在按元素修改 ans
向量,而不是整个向量本身。因此,yes
和 no
中的属性将被删除。
ans <- TRUE
ans[1] <- years(1)
ans
# [1] 0
以下内容来自帮助文件。 “答案的模式将从逻辑中强制转换”,首先从 yes
值开始。
mode(years(1))
# [1] "numeric"
Value
A vector of the same length and attributes (including dimensions and "class") as test and data values from the values of yes or no. The mode of the answer will be coerced from logical to accommodate first any values taken from yes and then any values taken from no.
关于r - 如果条件包含 lubridate 包中的 `years` 函数,ifelse 命令总是返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72749363/