简体   繁体   中英

How to populate a list with vectors in R

I am trying to populate a list with vectors that come out of some operations happening inside a for loop.

var_hyp1 <- list()
var_hyp2 <- list()
var_hyp3 <- list()

for (i in 1:9){
  
  vec1 <- rnorm(1000)  
  vec2 <- rnorm(1000)
  vec3 <- rnorm(1000)
  vec4 <- rnorm(1000)
    
  var_hyp1 <- vec2 - vec1
  var_hyp2 <- vec4 - vec3
  var_hyp3 <- vec4 - vec1
  

  var_hyp1[[i]] <- var_hyp1
  var_hyp2[[i]] <- var_hyp2
  var_hyp3[[i]] <- var_hyp3
}

In which I keep having this error that I cannot understand.

Error in var_hyp1[[i]] <- var_hyp1 : 
  more elements supplied than there are to replace

I appreciate any insight.

Maybe this is what you're looking for? In your code, you're assigning a list into a list at 'I', but this probably isn't what you want. Let me know if this isn't what you want.

var_hyp1 <- list()
var_hyp2 <- list()
var_hyp3 <- list()

for (i in 1:9){
  
  vec1 <- rnorm(1000)  
  vec2 <- rnorm(1000)
  vec3 <- rnorm(1000)
  vec4 <- rnorm(1000)
  
  var_hyp1[[i]] <- vec2 - vec1
  var_hyp2[[i]] <- vec4 - vec3
  var_hyp3[[i]] <- vec4 - vec1
  
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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