0

I have a numeric matrix as follows

1 2 3 4 5 
1 4 6 1 4
2 4 1 6 8 
1 7 3 6 7
1 4 5 6 2

I have a vector c(2,4,2,6,8)

For each row I want to take the corresponding value in the vector and make a new matrix where all the values in the row greater than the vector value goes to 0.

The output should look like

1 2 0 0 0   # greater than 2 is changed to 0
1 4 0 1 4   # greater than 4 changed to 0
2 0 1 0 0   # greater than 2 changed to 0
1 0 3 6 0   # greater than 6 changed to 0
1 4 5 6 2   # greater than 8 changed to 0

Is there a way to do this without actually coding through a loop?

Ricardo Oliveros-Ramos
  • 4,322
  • 2
  • 25
  • 42

2 Answers2

3
DF <- read.table(text="1 2 3 4 5
1 4 6 1 4
2 4 1 6 8
1 7 3 6 7
1 4 5 6 2") 

m <- as.matrix(DF)
v <- c(2,4,2,6,8)

m * (m <= v)
#      V1 V2 V3 V4 V5
# [1,]  1  2  0  0  0
# [2,]  1  4  0  1  4
# [3,]  2  0  1  0  0
# [4,]  1  0  3  6  0
# [5,]  1  4  5  6  2
Roland
  • 127,288
  • 10
  • 191
  • 288
1

Yes, you can:

m <- matrix(sample(10,25,replace = TRUE),5,5)
> m[m > matrix(c(2,6,8,4,5),5,5)] <- 0

I made up a differently example, since yours was not easily reproducible.

Or as DWin points out, R will do the matrix construction for you:

m[m > c(2,6,8,4,5)] <- 0
joran
  • 169,992
  • 32
  • 429
  • 468