r - 如果条件包含 lubridate 包中的 `years` 函数,ifelse 命令总是返回 0

标签 r if-statement lubridate

我有一个 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 向量,而不是整个向量本身。因此,yesno 中的属性将被删除。

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/

相关文章:

r - knitr 可以尊重 message(...,appendLF = FALSE) 调用吗?

php - 如何检查特定的键数组元素是否存在?

r 检查 Sys.time() 是否在一天中给定的时间间隔内

r - 日期列中的不同条目,目的是在删除之前保留列。如何最好地清理这样的 "date"列?

r - 如何使用函数查看文件中的结果并*应用?

r - 在 R 中,为什么 is.integer(1) 返回 FALSE?

矩阵的R dimnames,奇怪的行为

Python:for 循环内 if 语句的 "breaking out"

excel - 复数中频公式

r - lubridate::floor_date(x, "14 days"):如何防止新月份重新启动?