如何遍历矩阵并更改某些元素?

时间:2020-01-31 14:49:44

标签: r

此刻我的代码如下

for(i in 1:3500){
  if ((matrix$column[i] == 'yes')|((matrix$column[i] == 'no'))){
    matrix$contact[i] = 'maybe'

  }
}

基本上,如果元素等于“是”或“否”,我想将其更改为“也许”。 我目前遇到的错误是

1: In `[<-.factor`(`*tmp*`, i, value = "maybe") :
  invalid factor level, NA generated

2 个答案:

答案 0 :(得分:0)

您将收到此错误,因为您要更改的数组或向量是因子类型,并且没有级别为maybe

如果要添加或更新factor变量,首先需要将其更改为character类型。您应该在for循环之前执行此操作。您可以使用as.character(yourfactorvariable)方法对其进行修复。

答案 1 :(得分:0)

您不必使用循环。相反,您可以只使用apply

一些数据:

mtx <- matrix(NA, nrow = 8, ncol = 4)
y <- c("yes", "no", "other")
set.seed(123)
mtx <- apply(mtx, 2, function(x) sample(y, 8, replace = T)); mtx
     [,1]    [,2]    [,3]    [,4]   
[1,] "other" "other" "other" "other"
[2,] "other" "yes"   "other" "no"   
[3,] "other" "no"    "yes"   "yes"  
[4,] "no"    "no"    "yes"   "no"   
[5,] "other" "yes"   "yes"   "other"
[6,] "no"    "no"    "yes"   "no"   
[7,] "no"    "other" "other" "yes"  
[8,] "no"    "yes"   "no"    "other"

这是您进行转换的方式:

apply(mtx, 2, function(x) ifelse(x=="yes"|x=="no", "maybe", x))
     [,1]    [,2]    [,3]    [,4]   
[1,] "other" "other" "other" "other"
[2,] "other" "maybe" "other" "maybe"
[3,] "other" "maybe" "maybe" "maybe"
[4,] "maybe" "maybe" "maybe" "maybe"
[5,] "other" "maybe" "maybe" "other"
[6,] "maybe" "maybe" "maybe" "maybe"
[7,] "maybe" "other" "other" "maybe"
[8,] "maybe" "maybe" "maybe" "other"