如果其他循环不起作用

罗莎莉·范德梅多

我是 R Studio 的初学者,所以希望有人能帮助我解决这个问题。案例:我想做一个 if else 循环。我为l时间m矩阵制作了以下代码

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章