简体   繁体   English

我的矩阵填充代码给出了NA?

[英]My matrix-populating code is giving NAs?

I am trying to create a matrix of values from an equation inside of a for loop. 我正在尝试从for循环内的方程式创建值矩阵。 I keep getting "NA" filled in all of the indices. 我一直在所有索引中填充“ NA”。 How do I put the values from the y equation into the matrix steal ? 如何将y方程中的值放入矩阵steal

set.seed(1234)

row = 10
col = 100
p1 = list(runif(250, 0, 0.250))
p2 = list(runif( 500, 0.250, 0.750))
pBASP = list(runif(1000, 0, 1)) 

steal = matrix(data=NA, nrow=10, ncol=100)
as.data.frame(steal)

y = matrix(data=NA, nrow=10, ncol=100)
as.data.frame(y)

success <- function(p1, p2, pBASP) {

  for(i in 1:row) {  
    for(j in 1:col) {      
      y[i,j] <- (p1/p2) + pBASP

      if(y[i,j] > 0.750){        
        steal[i,j] <- y[i,j]        
      }      
    }  
  }

  return(steal)
}

#plot(y, hy, type="l", lty=2, xlab="y value",
# ylab="Density", main="Batting Average with RISP")

Are you able to run your function in the current form? 您能以当前形式运行函数吗?

The problem is that p1 , p2 , and pBASP are all lists which makes this call to fail: 问题是p1p2pBASP都是使此调用失败的列表:

y[ i, j ] <- ( p1 / p2 ) + pBASP

To actually run it i had to access items within the lists. 要实际运行它,我必须访问列表中的项目。 I do not know what's the purpose of the function so I only focused on making it run and accessed i th element of each list: 我不知道有什么功能的目的,所以我只专注于使其运行和访问i个每个列表的元素:

 y[ i, j ] <- ( p1[[1]][[i]] / p2[[1]][[i]] ) + pBASP[[1]][[i]]

This generates a result and actually populates the steal collection. 这会产生一个结果,实际上填充steal集合。

Also, is there any particular reason to create p1 , p2 , and pBASP as lists and not vectors (using c() function.) Making it vector would simplify the access syntax to this: 另外,是否有任何特殊原因将p1p2pBASP创建为列表而不是向量(使用c()函数。)将其设置为向量将简化对此的访问语法:

 y[ i, j ] <- ( p1[i] / p2[i] ) + pBASP[i]

Here's my "best guess" based on how I'm interpreting the code you've written. 这是根据我对您编写的代码的解释方式得出的“最佳猜测”。 I'll modify my response if it doesn't capture what you're trying to do. 如果无法捕获您要尝试的操作,我将对其进行修改。

# I'm changing the dimensions of `p1` and `p2` to match the matrices:
p1 <- runif(10,  0, 0.25)
p2 <- runif(100, 0.25, 0.75)
pBASP <- matrix(runif(1000, 0, 1), ncol = 100, nrow = 10)

y <- outer(p1, p2, "/") + pBASP # this creates y without any loops

steal <- y  
steal[steal <= 0.75] <- NA # remove the values of steal that you don't want.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM