0

I have a simple ifelse statement. I expect result to be an array of length 6: c("known", ... ). But I am getting an array of length 1: "known"

x <- 6
ifelse(x > 5, rep("known", x), rep("unknown", x))

SiH
  • 1,378
  • 4
  • 18

1 Answers1

2

See ?ifelse. It returns:

A vector of the same length and attributes (including dimensions and "class") as test

You want if and else:

if (x > 5) {
  rep("known", x)
} 
else
{
  rep("unknown", x)
}

Or you could use dplyr::case_when:

library(dplyr)

case_when(x > 5 ~ rep("known", x), 
          TRUE ~ rep("unknown", x))
neilfws
  • 32,751
  • 5
  • 50
  • 63