简体   繁体   中英

How to store results of a for loop in a vector or a list in R

I want to run a simple for loop and store values in a list or a vector. For example:

ex = c(10,11,17)



for (i in (0:length(ex))){
  if ex[i] < 12 {
    # store the value in a vector
  }
}

How can I do this, when I do not know the length of the vector and therefore cannot define it first?

Another base R option is using na.omit + ifelse

na.omit(ifelse(ex<12,ex,NA))

You can do this without for loop:

ex[ex < 12]
#[1] 10 11

Or using Filter :

Filter(function(x) x < 12, ex)

However, if you want to do this with for loop you can try:

count <- 1
result_vec <- numeric()

for (i in ex) {
   if (i < 12) {
    result_vec[count] <- i
    count <- count + 1
  }
}

You can allocate a max possible size vector and only partially fill it, then reduce it down.

ex = c(10,11,17,9,14,1,20,1)
store <- list(length(ex))
for (i in (1:length(ex))){
  if(ex[i] < 12){
    store[[i]] <- ex[i]
  }
}
unlist(store)

[1] 10 11  9  1  1

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