我正在尝试根据另一个矩阵z
定义新的矩阵x
。这就是我所做的:
x = structure(
.Data = c(5012, 3257,2638,-898,1734,2642,1828,599,-54,172,
-106,4179,-1111,5270,3116,1817,-103,0,535,NA,
3410,5582,4881,2268,2594,3479,0,603,NA, NA,
5655,5900,4211,5500,2159,2658,984, NA, NA, NA,
1092,8473,6271,6333,3786,-225, NA, NA, NA, NA,
1513,4932,5257,1233,2917, NA , NA, NA, NA, NA,
-557,3463,6926,1368, NA, NA, NA, NA, NA, NA,
1351,5596,6165, NA, NA, NA, NA, NA, NA, NA,
3133,2262, NA, NA, NA , NA , NA , NA, NA , NA,
2063, NA, NA, NA , NA , NA , NA, NA , NA, NA),
.Dim = c(10,10))
x = t(x)
r=ncol(x)
z = matrix(ncol = r, nrow = r)
for(i in 1:r){
for(j in 1:r){
if(x[i,j]>0){
z[i,j] = 1
}
else if(x[i,j]<0){
z[i,j] = -1
}
else {
z[i,j]=0
}
}
}
但是我遇到了错误:
Error in if (x[i, j] > 0) { : missing value where TRUE/FALSE needed
我该如何解决?
答案 0 :(得分:2)
当if
命中NA
for(i in 1:r){
for(j in 1:r){
if(!is.na(x[i,j]) & x[i,j]>0){
z[i,j] = 1
}
else if(!is.na(x[i,j]) & x[i,j]<0){
z[i,j] = -1
}
else {
z[i,j]=0
}
}
}