1

I am writing a simple ifelse statement following another , where I'm trying to classify the index into three groups ( >= 0.8, 0.8 to -0.8, <= -0.8)

I keep getting an error:

In if (df$index >= 0.8) { : the condition has length > 1 and only the first element will be used

index <- c(0.8,0.2,-0.2,0,-1,-1)
df <- data.frame(index)
df$indexclass <- NA


df$indexclass  <- if (df$index >= 0.8) {
  df$indexclass  <- "P"
} else if (df$index <= (-0.8)) {
  df$indexclass  <- "A"
} else { df$indexclass <- "S"}
Rspacer
  • 2,369
  • 1
  • 14
  • 40

1 Answers1

4

We can use ifelse instead of if/else because if/else expects a vector of length 1 and is not vectorized for length greater than 1.

df$indexclass  <- with(df, ifelse(index >= 0.8, "P",
        ifelse(index <= (-0.8),  "A", "S")))
df$indexclass
#[1] "P" "S" "S" "S" "A" "A"

If there are multiple comparisons, an option would be either cut orfindInterval

c("A", "S","P")[with(df,  findInterval(index, c(-0.8, 0.8)))  + 1]
#[1] "P" "S" "S" "S" "A" "A"
akrun
  • 874,273
  • 37
  • 540
  • 662