Home > other >  How do I replace a value in a matrix/dataframe if that value is less than the corresponding value in
How do I replace a value in a matrix/dataframe if that value is less than the corresponding value in

Time:02-25

I have a (20x12)matrix with numerical values and a list of 12 numbers. If a value in the matrix is less than the value in the list in the corresponding column index, I would like to replace it. How can I do it?

mat <- matrix(rpois(240,10),ncol=12)

list_to_replace <- rpois(12,10)

CodePudding user response:

I think this is what is desired. Use the same logical index to pick out the positions of the possible replacements and the re-assignments:

t( apply(mat, 1, function(r) {
       r[ r < list_to_replace] <- list_to_replace[ r < list_to_replace]; r}) )

The t is needed to transpose back because the apply function always delivers column-oriented result, even when the input is rowwise.

BTW; you would be well advised to only use the term "list" when referring to an R object with class "list". What you have is a "vector".

CodePudding user response:

You could use the code below:

index <- t(t(mat) < list_to_replace)
mat[index] <- list_to_replace[which(index, TRUE)[, 2]]
  •  Tags:  
  • r
  • Related