r - R 中 ifelse() 的奇怪行为 : when are the values evaluated?

标签 r if-statement nan sqrt

我有以下数据:

df = data.frame(
  stat = c('mean', 'var'),
  value = c(-9, 10))

假设如果“stat”是“var”,我想取“value”的平方,如果不是,则不执行任何操作。

df %>% 
  mutate(
   value = ifelse(stat=='var', sqrt(value), value))

我收到警告:

Warning message:
In sqrt(-9) : NaNs produced

为什么我会收到警告?不应计算值 sqrt(-9) 因为“值”是“平均值”

最佳答案

根据ifelse文档

 If ‘yes’ or ‘no’ are too short, their elements are recycled.
 ‘yes’ will be evaluated if and only if any element of ‘test’ is
 true, and analogously for ‘no’.

您已将其解释为意味着将以逐元素方式绕过"is"或“否”。

但是,似乎这不是文档的意思。这意味着,除非测试中的所有元素都为 true 或 false,否则将进行评估。

这意味着,只要您的测试至少有一个 true 和至少一个 false,那么将为测试中的每个元素预先计算 yes 和 no,并且只有在评估该元素之后,才会给出适当的响应已选择。

关于r - R 中 ifelse() 的奇怪行为 : when are the values evaluated?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61913639/

相关文章:

bash - tcsh 中的 IF 语句错误

php 输出带有记录限制的 txt 文件并按唯一的县名称分组

python - 将 numpy float 组转换为整数,替换 NaN 值

r - 如何使这个嵌套 for 循环工作得更快

R Shiny - 如果两个输入具有相同的值,如何显示反馈消息(使用shinyFeedback)

Java:如何测试输入是 double 还是 int

java - NaN 的总和 : How is the underlying bit pattern calculated?

list - R:将列表打印到文本文件

r - 在 R 中使用 twitteR 时出现 oauth 握手错误

python - pandas *有效地*按组将有效值复制到其他行