简体   繁体   中英

How can I store the value of each iteration of a FOR loop into a vector in R?

I need to store the variable "result" into a vector. I have been trying for days. Still can't get through it



for(i in 1:10)
{
  avgcol<-c(q[i])
  numofNA<-sum(is.na(clnvar[i,]))
  monthsnoNA<-31-numofNA
  result=avgcol/monthsnoNA
  
newvar<-c(result,i)

  
  
}

I Would like to have a vector with all the values gotten from the iterations of the for loop. The solution I tried won't work. It does not create a vector. What am I doing wrong?

Initialize the result outside and then assign based on the index

result <- numeric(10)
for(i in 1:10)
 {
   avgcol <-c(q[i])
  numofNA <- sum(is.na(clnvar[i,]))
  monthsnoNA<-31-numofNA
  result[i] <- avgcol/monthsnoNA
}

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