0

In GNU R, I wish to create an array of strings from an array of numbers in which I categorise number intervals. For example:

x <- c(1:6)

The new array shall categorise number intervals as for example:

x <= 2 --> "Category A"
x > 2 & x <= 5 --> "Category B"
x > 5 -- > "Category C"

So that the new array takes the form of:

x1
[1] "A" "A" "B" "B" "B" "C"

How do I do this?

2 Answers2

1

You can try cut

 x1 <- as.character(cut(x, breaks=c(0, 2, 5, Inf), labels=LETTERS[1:3]))
 x1
 #[1] "A" "A" "B" "B" "B" "C"
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You can use the sapply function if you need to do something else within the conditions:

sapply(x, function(x){
  if(x <= 2){
    "A"
  } else  if (x > 2 && x <= 5){
    "B"
  } else if (x > 5){
    "C"
  }  
})

[1] "A" "A" "B" "B" "B" "C"
ELCano
  • 156
  • 4