Reputation: 2825
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
Reputation: 102625
Another base R option is using na.omit
+ ifelse
na.omit(ifelse(ex<12,ex,NA))
Upvotes: 0
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
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