我有一个矩阵的例子,我想根据条件语句将矩阵的条目更改为
"YES"
或"NO"
。a<-c(5,1,0,3,2,0.6,1.6,7,9,0)
b<-c(11,0,1,18,11,11,0,13,20,10)
c<-c(10,20,0.7,0.8,0.3,0.4,0,0.9,1,1)
MAT<-cbind(a,b,c)
MAT
for (i in 1:nrow(MAT)){
for (j in 1:ncol(MAT)){
if (MAT[i,j]>5){
MAT[i,j]="YES"
} else {
MAT[i,j]="NO"
}
}
}
print(MAT)
我得到的输出是这样的,但是它是错误的。请告诉我问题出在哪里以及如何修复它?
a b c
[1,] "NO" "NO" "NO"
[2,] "NO" "NO" "NO"
[3,] "NO" "NO" "NO"
[4,] "NO" "NO" "NO"
[5,] "NO" "NO" "NO"
[6,] "NO" "NO" "NO"
[7,] "NO" "NO" "NO"
[8,] "YES" "NO" "NO"
[9,] "YES" "NO" "NO"
[10,] "NO" "NO" "NO"
MAT
后面的空括号是不必要的,因为ifelse
返回的值与其test
参数具有相同的形状。由于MAT>5
是一个矩阵,因此ifelse
的值也将是一个矩阵。 - Robert Hackenifelse
的输出将是一个向量(从其dim
属性中剥离的矩阵),这是不正确的。 - Robert Hacken