Home > Back-end >  Conditionally replace a value in a matrix with a new value if condition is TRUE
Conditionally replace a value in a matrix with a new value if condition is TRUE

Time:03-31

I am currently trying to create a new matrix by looping over the old one. The thing that I would want to change in the new matrix is replacing certain values with the character "recoding".Both of the matrixes should have 10 columns and 100 rows.

In the current case, the certain value is one that matches with on eof the values in vector_A.

e.g:

for (i in 1:10) {
  new_matrix[,i] <- old_matrix[,i]
  output_t_or_f <- is.element(new_matrix[,i],unlist(vector_A))
  if (any(output_t_or_f, na.rm = FALSE)) { 
    replace(new_matrix, list = new_matrix[,i], values = "recode")
  }   
}
    

so output_t_or_f should either take on the value TRUE or FALSE, depending on whether i is in vector_A and if output_t_or_f is TRUE then the old value should be replaced with the character "recode"

Currently the new_matrix looks just like the old_matrix so I guess there is a problem with the if statement?

Unfortunately, I can't really share my Data but I put some example data together: if old_matrix looks like this:

> old_matrix
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    6   11   16   21
[2,]    2    7   12   17   22
[3,]    3    8   13   18   23
[4,]    4    9   14   19   24
[5,]    5   10   15   20   25

and vector_A looks like this:

> vector_A
[1] 12 27 30 42 37  9

then the new matrix should looks like this:

new_matrix

     [,1] [,2]       [,3]       [,4] [,5]
[1,] "1"  "6"        "11"       "16" "21"
[2,] "2"  "7"        "recoding" "17" "22"
[3,] "3"  "8"        "13"       "18" "23"
[4,] "4"  "recoding" "14"       "19" "24"
[5,] "5"  "10"       "15"       "20" "25"

I am very new to R and can't seem to find the problem. Would appreciate any help!! Thanks :-)

CodePudding user response:

Since the replacements are the same in every column you shouldn't need a loop. Try this:

new_matrix <- old_matrix
new_matrix[new_matrix %in% vector_A] <- "recode"
  • Related