Setting matrix values ​​compared to a vector in R

I want to set NA in each element of the matrix, where the value in the column is greater than or equal to the value of this vector. For example, I can create a matrix:

set.seed(1)
zz <- matrix(data = round(10L * runif(12)), nrow = 4, ncol = 3)

what gives for zz:

     [,1] [,2] [,3]
[1,]    8    5    7
[2,]    6    5    1
[3,]    5   10    3
[4,]    9    1    9

and for the comparison vector (for example):

xx <- round(10L * runif(4))

where xx:

[1] 6 3 8 2

if I perform this operation:

apply(zz,2,function(x) x >= xx)

I get:

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

I want wherever I have a TRUE element, I want NA and wherever I have FALSE. I get a number in the zz matrix (e.g. manually ...):

NA  5  NA
NA  NA 1
5   NA 3
NA  1  NA

I can combine some "for" loops to do what I want, but is there a vector based way?

Thanks for any advice.

+4
source share
2 answers

You can simply do:

zz[zz>=xx] <- NA

#     [,1] [,2] [,3]
#[1,]   NA    5   NA
#[2,]   NA   NA    1
#[3,]    5   NA    3
#[4,]   NA    1   NA
+2

. (zz >= xx), NA^, NA TRUE 1 FALSE, "zz", NA , 1 'zz'.

NA^(zz >= xx)*zz
#     [,1] [,2] [,3]
#[1,]   NA    5   NA
#[2,]   NA   NA    1
#[3,]    5   NA    3
#[4,]   NA    1   NA

: ifelse

ifelse(zz >= xx, NA, zz)

zz <- structure(c(8, 6, 5, 9, 5, 5, 10, 1, 7, 1, 3, 9), .Dim = c(4L, 3L))
xx <- c(6, 3, 8, 2)
+2

Source: https://habr.com/ru/post/1655204/


All Articles