Skip to content
Prev 389005 / 398506 Next

conditional replacement of elements of matrix with another matrix column

Hello,

With the new data, here are two ways.
The first with a for loop. I find it simple and readable.


for(b in unique(B[,1])){
   A[which(A[,1] == b), 2] <- B[which(B[,1] == b), 2]
}
na <- is.na(A[,2])
A[!na, 2]

sum(!na)               # [1] 216
sum(A[,1] %in% B[,1])  # [1] 216

# Another way, with merge
mrg <- merge(as.data.frame(A), as.data.frame(B), by = "V1", all.x = 
TRUE)[c(1, 3)]
sum(!is.na(mrg[[2]]))  # [1] 216

identical(A[,2], mrg[[2]])  # [1] TRUE


Note that mrg is a data.frame, you can coerce back to matrix


A <- as.matrix(mrg)


Hope this helps,

Rui Barradas


?s 23:00 de 01/09/21, Eliza Botto escreveu: