简体   繁体   中英

Creating conditional axis labels in R?

I'm wondering why, when running the below R function, I get the following warning:

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

Since everything works fine except this warning message, I was wondering how I could eliminate this warning message?

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))

Assuming that labels is a vector, is.na(labels) will return a vector of TRUE/FALSE values. In R, the standard if statement must evaluate to a single TRUE/FALSE value. The warning message is telling you that if produced multiple values and is evaluating truth based on the first one.

If your goal is to check to see if any values in labels are NA , do:

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

If your goal is to replace the NA elements of some vector with the values of another vector, you probably want ifelse() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM