【问题标题】:Creating conditional axis labels in R?在 R 中创建条件轴标签?
【发布时间】:2018-05-14 14:13:56
【问题描述】:

我想知道为什么在运行以下 R 函数时,我收到以下警告:

Warning message: In if (is.na(labels)) axTicks(2) else labels : the condition has length > 1 and only the first element will be used

由于除了此警告消息外一切正常,我想知道如何消除此警告消息?

bb <- function(labels = NA){

 plot(1, yaxt = "n")

 lab <- if(is.na(labels)) axTicks(2) else labels ## Why this gives a warning message?

 axis(2, at = axTicks(2), labels = lab)
}
# Example of use:
bb(labels = paste0("Hi ", 1:5))

【问题讨论】:

  • is.na(labels) 将返回一个由 TRUE/FALSE 值组成的 vector,在 if 语句中只计算第一个值。您是否尝试替换 labels 中的任何 NA 值?
  • @jdobres,没错!

标签: r function if-statement plot


【解决方案1】:

假设 labels 是一个向量,is.na(labels) 将返回一个 TRUE/FALSE 值的向量。在 R 中,标准的 if 语句必须评估为 单个 TRUE/FALSE 值。警告消息告诉您if 产生了多个值,并且正在根据第一个值评估真相。

如果您的目标是检查labels 中的任何 值是否为NA,请执行以下操作:

if (any(is.na(labels))) {
  ...
}

如果您的目标是用另一个向量的值替换某个向量的NA 元素,您可能需要ifelse()

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    相关资源
    最近更新 更多