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?

0

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.