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

Avi Gross @v|gro@@ @end|ng |rom ver|zon@net
Thu Sep 2 00:06:22 CEST 2021

```Why would you ask your question without mentioning that the two vectors may
be of unequal length when your abbreviated example was not like that!

You have two CASES here. In one A is longer and in one B is longer. When
they are the same, it does not matter.

So in your scenario, consider looking at length(A) and length(B) and
adjusting whatever method you use carefully. You now might need to use 1:N
notation to limit what you are doing so you do not access values out of
bounds.

Not going to do it for you. I see others have also supplied variants and .

From: Eliza Botto <eliza_botto using outlook.com>
Sent: Wednesday, September 1, 2021 6:00 PM
To: r-help using r-project.org; Mohammad Tanvir Ahamed <mashranga using yahoo.com>; Avi
Gross <avigross using verizon.net>; Richard M. Heiberger <rmh using temple.edu>
Subject: Re: [R] conditional replacement of elements of matrix with another
matrix column

I thank you all. But the code doesn't work on my different dataset where A
and B have different column lengths. For example,

> dput(A)

structure(c(17897, 17897, 17897, 17897, 17897, 17897, 17897,

17897, 17897, 17897, 17897, 17897, 17897, 17897, 17897, 17897,

SNIP

Can you please guide me how to implement the given code on this dataset?

_____

From: Mohammad Tanvir Ahamed <mashranga using yahoo.com>
Sent: Wednesday 1 September 2021 21:48
To: r-help using r-project.org <r-help using r-project.org>; Eliza Botto
<eliza_botto using outlook.com>
Subject: Re: [R] conditional replacement of elements of matrix with another
matrix column

C1 <- A
C1[,2][which(B[,1]%in%A[,1])] <- B[,2][which(B[,1]%in%A[,1])]

Regards.............
Tanvir Ahamed

On Wednesday, 1 September 2021, 11:00:16 pm GMT+2, Eliza Botto
<eliza_botto using outlook.com> wrote:

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