lightsnail lightsnail - 1 month ago 7
R Question

Replace multiple values in a matrix

a
is a matrix:

a <- matrix(1:9,3)

> a
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9


I want to replace all the 1 to good, all the 4 to medium, and all the 9 to bad.

I use the following code:

a[a==1] <- "good"
a[a==4] <- "medium"
a[a==9] <- "bad"

> a
[,1] [,2] [,3]
[1,] "good" "medium" "7"
[2,] "2" "5" "8"
[3,] "3" "6" "bad"


It works, but is this the simplest way to work it out? Can I combine these codes into one command?

Answer

Using cut():

matrix(cut(a, breaks = c(0:9),
           labels = c("good", 2:3, "medium", 5:8, "bad")), 3)

But not really happy with manual labels bit.

Maybe using match(), more flexible:

res <- matrix(c("good", "medium", "bad")[match(a, c(1, 4, 9))], 3)
res <- ifelse(is.na(res), a, res)