lightsnail
lightsnail

Reputation: 788

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?

Upvotes: 4

Views: 1188

Answers (2)

zx8754
zx8754

Reputation: 56004

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)

Upvotes: 4

Rich Scriven
Rich Scriven

Reputation: 99331

car::recode() does nicely here, returning the same matrix structure as was given as input.

car::recode(a, "1='good';4='medium';9='bad'")
#      [,1]   [,2]     [,3] 
# [1,] "good" "medium" "7"  
# [2,] "2"    "5"      "8"  
# [3,] "3"    "6"      "bad"

Upvotes: 2

Related Questions