Replacing matrix cells for corresponding row names

I'm working with a matrix that looks like this input.

enter image description here

I'm trying to replace numbers on column 2 by their corresponding row name. I.e. all 1s would be replaced by row.name(matrix). Thus, I'd have the following output.

enter image description here

The actual matrix is too large for loop application... I'm sorry I'm using images since I found it easier to represent this on excel. I'm also sorry about being quite new at R...

Upvotes: 1

Views: 57

Answers (1)

LAP
LAP

Reputation: 6685

Vectorized approach (should be the fastest you can get):

mat <- matrix(c(letters[1:11], 1,1,1,2,2,3,3,3,4,4,4), ncol = 2)
    colnames(mat) <- c("A", "B")
    rownames(mat) <- 1:11

> mat
   A   B  
1  "a" "1"
2  "b" "1"
3  "c" "1"
4  "d" "2"
5  "e" "2"
6  "f" "3"
7  "g" "3"
8  "h" "3"
9  "i" "4"
10 "j" "4"
11 "k" "4"


mat[, "B"] <- mat[as.numeric(mat[, "B"]), "A"]
> mat
   A   B  
1  "a" "a"
2  "b" "a"
3  "c" "a"
4  "d" "b"
5  "e" "b"
6  "f" "c"
7  "g" "c"
8  "h" "c"
9  "i" "d"
10 "j" "d"
11 "k" "d"

Or you could use sapply:

mat[, "B"] <- sapply(mat[, "B"], function(x) mat[as.numeric(x), "A"])

Edit: I've put the vectorized solution at the top, as this is clearly the faster (or even fastest?) approach.

Upvotes: 3

Related Questions