0

I am trying to create a new factor variable that is conditional based on a numeric variable within my dataframe. my ifelse argument works perfectly when I supply it a single inequality, but for the two categories that require a compound inequality, it doesn't work. I'm familiar with logic and conditions in other languages, and I'm thinking just my syntax is off?

Also, there seems to be times when you can use '&' and times to use '&&'. I'm used to always using '&&', so what is the difference here?

data$bin<-as.factor(ifelse(data$internet<=2.3225,"one",
                      ifelse(data$internet>2.3225 && data$internet<=4.425,"two",
                      ifelse(data$internet>4.425 && data$internet<=6.5275,"three",
                      ifelse(data$internet>6.5275,"four",NA)))))
KLB
  • 57
  • 7
  • && doesn't vectorize. Unless you want to compare a single element to a single element, you should use &. – iod Oct 16 '18 at 20:40
  • 2
    Use `cut`. [Convert continuous numeric values to discrete categories defined by intervals](https://stackoverflow.com/questions/13559076/convert-continuous-numeric-values-to-discrete-categories-defined-by-intervals) – Henrik Oct 16 '18 at 20:40
  • Thank @iod. That makes sense and fixed it! – KLB Oct 16 '18 at 20:42
  • But do follow Henrik's advice on using cut() instead of a series of ifelses. – iod Oct 16 '18 at 20:48

1 Answers1

0

&& doesn't vectorize. Unless you want to compare a single element to a single element, you should use &.

iod
  • 7,412
  • 2
  • 17
  • 36