Skip to content
Back to formatted view

Raw Message

Message-ID: <04b701d79f79$23534d40$69f9e7c0$@verizon.net>
Date: 2021-09-01T21:34:25Z
From: Avi Gross
Subject: conditional replacement of elements of matrix with another matrix column
In-Reply-To: <AS8P194MB099980A639EB635D298BF6DB9ACD9@AS8P194MB0999.EURP194.PROD.OUTLOOK.COM>

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]
[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 at r-project.org> On Behalf Of Eliza Botto
Sent: Wednesday, September 1, 2021 5:00 PM
To: r-help at 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?


Thanks in advance,

Eliza Botto

	[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.