Re: [R] conditional replacement of elements of matrix with another matrix column

2021-09-02 Thread Rui Barradas
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,

Re: [R] conditional replacement of elements of matrix with another matrix column

2021-09-01 Thread Avi Gross via R-help
; Mohammad Tanvir Ahamed ; Avi Gross ; Richard M. Heiberger 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) str

Re: [R] conditional replacement of elements of matrix with another matrix column

2021-09-01 Thread Avi Gross via R-help
: Wednesday, September 1, 2021 6:00 PM To: r-help@r-project.org; Mohammad Tanvir Ahamed ; Avi Gross ; Richard M. Heiberger 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

Re: [R] conditional replacement of elements of matrix with another matrix column

2021-09-01 Thread Eliza Botto
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, 17897, 17897, 17897, 17897, 17897, 178

Re: [R] conditional replacement of elements of matrix with another matrix column

2021-09-01 Thread Mohammad Tanvir Ahamed via R-help
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 wrote: deaR useRs, I have the matrix "A" and matrix "B" and I want the matrix "C". Is there a way of doing it?

Re: [R] conditional replacement of elements of matrix with another matrix column

2021-09-01 Thread Avi Gross via R-help
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 T