How to store a value object extracted from the for statement.

#--------code-----------------
ve <- NULL

for(i in 1:20) {
if(i%%2==0) {
ve[i] <- print(i)
}
}

ve

#--------------------result----------------

ve
[1] NA 2 NA 4 NA 6 NA 8 NA 10 NA 12 NA 14 NA 16 NA 18 NA 20

Q: How can I store only extracts from the for statement in an object called ve?
ex) >ve
[1] 2 4 6 8 10 12 14 16 18 20

ve[!is.na(ve)]

startz gave an excellent one line solution to finesse your first result to the desired outcome.
I will just show you for completeness, two other approaches.
The first is based on the original creation, so it does not create NA's, this is done by using a second counting variable (j).

ve <- NULL
j <- 0
for(i in 1:20) {
  if(i%%2==0) {
    ve[j] <- print(i)
    j <- j + 1
  }
}

finally here is a one liner, which avoids the use of explicit for loop directly and immediately gives the desired results with fewest keypresses.

(ve2 <- 2* 1:10)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.