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 1 with good, all 4 with medium, and all 9 with bad.

I am using 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"

This works, but is this the easiest way to solve it? Can I combine these codes into one command?

+4
source share
2 answers

Usage cut():

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

But not very happy with the recording of manual tags.

Possible use match(), more flexible:

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

car::recode() here is fine, returning the same matrix structure as 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"
+2
source

Source: https://habr.com/ru/post/1657315/


All Articles