如果条件为真,则有条件地用新值替换矩阵中的值

Conditionally replace a value in a matrix with a new value if condition is TRUE

我目前正在尝试通过遍历旧矩阵来创建新矩阵。我想在新矩阵中改变的是用字符“recoding”替换某些值。两个矩阵都应该有 10 列和 100 行。

在当前情况下,特定值是与 vector_A.

中的一个值匹配的值

例如:

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")
  }   
}
    

所以 output_t_or_f 应该取值 TRUEFALSE,这取决于我是否在 vector_A 如果 output_t_or_fTRUE 则旧值应该替换为字符 "recode"

目前 new_matrix 看起来就像 old_matrix 所以我猜 if 语句有问题?

不幸的是,我无法真正分享我的数据,但我将一些示例数据放在一起: 如果 old_matrix 看起来像这样:

> 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

和 vector_A 看起来像这样:

> vector_A
[1] 12 27 30 42 37  9

那么新矩阵应该是这样的:

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"

我是 R 的新手,似乎找不到问题所在。将不胜感激任何帮助! 谢谢:-)

由于每一列中的替换都是相同的,因此您不需要循环。试试这个:

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