# [R] conditional replacement of elements of matrix with another matrix column

Avi Gross @v|gro@@ @end|ng |rom ver|zon@net
Wed Sep 1 23:34:25 CEST 2021

```Seems trivial enough Elizabeth, either using a matrix or data.frame.

R is vectorized mostly so A[,1] notation selects a column all at once. Your
condition is thus:

A[,1] == B[,1]

After using your sample data to initialize an A and a B, I get this:

> A[,1] == B[,1]
 FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE

That Boolean vector can be used to index either of your matrices or any that
have the same number of rows:

Here is one solution using the vectorized ifelse() function:

using <- A[,1] == B[,1]

C <- A

C[, 2 ] <- ifelse(using, B[, 2], A[, 2])

I show the results below and you can tell us if that matches your need on
this sample data:

> A
[,1] [,2]
[1,]   12   NA
[2,]   12   NA
[3,]   12   NA
[4,]   13   NA
[5,]   13   NA
[6,]   13   NA
[7,]   14   NA
[8,]   14   NA
[9,]   14   NA
> B
[,1] [,2]
[1,]   11    6
[2,]   11    7
[3,]   11    8
[4,]   13    9
[5,]   13   10
[6,]   13   11
[7,]   14   12
[8,]   14   13
[9,]   14   14
> C
[,1] [,2]
[1,]   12   NA
[2,]   12   NA
[3,]   12   NA
[4,]   13    9
[5,]   13   10
[6,]   13   11
[7,]   14   12
[8,]   14   13
[9,]   14   14

Of course, the above can be done in fewer steps or many other ways.

-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of Eliza Botto
Sent: Wednesday, September 1, 2021 5:00 PM
To: r-help using r-project.org
Subject: [R] conditional replacement of elements of matrix with another
matrix column

deaR useRs,

I have the matrix "A" and matrix "B" and I want the matrix "C". Is there a
way of doing it?

> dput(A)

structure(c(12, 12, 12, 13, 13, 13, 14, 14, 14, NA, NA, NA, NA, NA, NA, NA,
NA, NA), .Dim = c(9L, 2L))

> dput(B)

structure(c(11, 11, 11, 13, 13, 13, 14, 14, 14, 6, 7, 8, 9, 10, 11, 12, 13,
14), .Dim = c(9L, 2L))

> dput(C)

structure(c(12, 12, 12, 13, 13, 13, 14, 14, 14, NA, NA, NA, 9, 10, 11, 12,
13, 14), .Dim = c(9L, 2L))

Precisely, I want to replace the elements of 2nd column of A with those of B
provided the elements of 1st column match. Is there a single line loop or
code for that?

Eliza Botto

[[alternative HTML version deleted]]

______________________________________________
R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help