Asteroid098
Asteroid098

Reputation: 2825

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?

Upvotes: 0

Views: 59

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 102625

Another base R option is using na.omit + ifelse

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

Upvotes: 0

Henri Chung
Henri Chung

Reputation: 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

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389235

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
  }
}

Upvotes: 0

Related Questions