Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array/matrix comparison by row instead of column

Tags:

r

matrix

I need to compare each item in an array against every element in a matrix. The matrix and array can be any size. I can't use loops or if statements - mainly functions like apply(), ifelse(), and so on. NA data can be ignored. Here is an example:

x <- c(1,0,1,0,1,1,1,1,0,1,0,1)
y <- c(1, NA, 1, NA)

The y array needs to compare, in rows, to x - so that after each element in y has compared itself to x, y continues comparing to x as a new row. The solution I want is:

[,1] [,2] [,3] [,4]
[1,] TRUE NA TRUE NA
[2,] TRUE NA TRUE NA
[3,] FALSE  NA FALSE  NA

This function compares with logical equivalence:

answer <- function(x,y){
  z <- x == y
  print(z)
}

The solution returns the correct answers but in a single row, where the next row should begin after the second NA.

[1]  TRUE    NA  TRUE    NA  TRUE    NA  TRUE    NA FALSE    NA FALSE    NA

When I try to turn that answer into a matrix with column length(y) - 4 in this case - the output isn't correct.

answer <- function(x,y){
  z <- x == y
  z2 <- matrix(z, ncol = length(y))
  print(z2)
}

The return is comparing values straight down by column:

[,1] [,2]  [,3]  [,4]
[1,] TRUE   NA  TRUE    NA
[2,]   NA TRUE    NA FALSE
[3,] TRUE   NA FALSE    NA

What can I use to make the comparison through each column in a row instead of each row in a column? Can I use apply(z, 1, some built-in function) or a nested apply(apply()) function? The difficulty has been to ensure that the resulting matrix is the correct size, with the correct answer, while compensating for any size array/matrix comparison.

like image 543
user12027316 Avatar asked Mar 30 '26 22:03

user12027316


1 Answers

We can make the lengths same and do the comparison

x == y[col(x)]
#       [,1] [,2]  [,3] [,4]
#[1,]  TRUE   NA  TRUE   NA
#[2,] FALSE   NA  TRUE   NA
#[3,]  TRUE   NA FALSE   NA

If the comparison is by row

x == y

Or

x== y[row(x)]

Or with sweep

sweep(x, 2, y, FUN = `==`)
#       [,1] [,2]  [,3] [,4]
#[1,]  TRUE   NA  TRUE   NA
#[2,] FALSE   NA  TRUE   NA
#[3,]  TRUE   NA FALSE   NA

data

x <- matrix(c(1,0,1,0,1,1,1,1,0,1,0,1), nrow=3, ncol=4)
y <- c(1, NA, 1, NA)
like image 116
akrun Avatar answered Apr 02 '26 13:04

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!