r - if 语句中的条件如何被强制为逻辑的?

标签 r

if 的文档说条件应该是(强调我的):

A length-one logical vector that is not NA. Conditions of length greater than one are currently accepted with a warning, but only the first element is used. An error is signalled instead when the environment variable _R_CHECK_LENGTH_1_CONDITION_ is set to true. Other types are coerced to logical if possible, ignoring any class.



强制是如何完成的,“忽略任何类”是什么意思?

例如,表达式 list(1)可以显式强制为 TRUEas.logical ,并被隐式考虑 TRUE等式比较:
> as.logical(list(1))
[1] TRUE
> list(1) == TRUE
[1] TRUE

那么,为什么以下操作会失败?
> if (list(1)) print("Passed test!")
Error in if (list(1)) print("Passed test!") : 
  argument is not interpretable as logical

最佳答案

发生这种情况是因为 如果 在 R 中使用主要对象类,在您的示例中,主要对象是列表而不是它们的内容,当您使用 as.logical 时,内部值被转换为逻辑返回数组。

a = list(x = 1, y = 0)
as.logical(a) # TRUE FALSE

仅当主要对象值为数字或某些特殊字符串时,才可以默认转换为逻辑值。
if("true") "ok" # ok
if(-1) "ok" # ok

val = 1
class(val) = "test"
attr(a, "something") = 0

if(val) "ok" # ok

[编辑_1]

另一个需要解释的好事情是关于因子:因子不是作为字符数组工作,而是作为数字数组工作。这些数字指的是值“标志”。
val = factor("TRUE", "FALSE")
as.numeric(val) # 1 (for TRUE), 2 (for FALSE)

关于r - if 语句中的条件如何被强制为逻辑的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55110378/

相关文章:

r - r 中的分组移动平均线

r - 使用 AND 或 OR 折叠 bool 向量

r - 如何以更快的方式处理和组合列表中的 data.frames

r - Bash/Linux 在 .txt 文件中查找非 ASCII 字符并将其替换为 ASCII 字符

r - 对于 lapply 中不同长度的列表

r - 整个facet_grid的极坐标/圆形布局

r - ggplot2 未正确保存 geom_raster() 绘图

r - R 中的否定,如何替换 R 中否定后面的单词?

r - 在 R 中使用 argmax 或更简单的东西

r - 仅保留最近的日期