如果其他循环不工作

if else loop not working

我是 R studio 的初学者,希望有人能帮助我解决这个问题。 案例:我想做一个 if else 循环。我为 lm 矩阵编写了以下代码:

for (i in 1:l){
  for (j in 1:m){ 
    if (is.na(quantilereturns[i,j]) < quantile(quantilereturns[,j], c(.1), na.rm=TRUE)) { 
      quantilereturns[i,j]    
    } else { (0) }
  }
}

总结: 我想创建一个矩阵,其值小于矩阵 quantilereturns 中某个向量的分位数。因此,当它们小于 10% 分位数时,它们将获得原始值,否则将为零。 该代码不会给出任何错误,但它也不会更改矩阵中的值。 有人能帮我吗?

您需要将结果分配给矩阵的一个单元格。我将以最近的其他线程的矩阵为例:

a <- c(4, -9, 2)
b <- c(-1, 3, -8)
c <- c(5, 2, 6)
d <- c(7, 9, -2)
matrix <- cbind(a,b,c,d)

d <- dim(matrix)
rows <- d[1]
columns <- d[2]

print("Before")
print(matrix)

for (i in 1:rows) {
  for (j in 1:columns) {
    if (is.na(matrix[i,j]) >= quantile(matrix[,j], c(.1), na.rm=TRUE)) {
      matrix[i,j] <- 0
    }
  }
}

print("After")
print(matrix)

这给出了

[1] "Before"
      a  b c  d
[1,]  4 -1 5  7
[2,] -9  3 2  9
[3,]  2 -8 6 -2
[1] "After"
     a b c d
[1,] 0 0 5 0
[2,] 0 0 2 0
[3,] 0 0 6 0

所以你要找的基本行是matrix[i,j] <- 0