Use 'for loop' to create vector

Hey, I am struck on a problem that requires to a vector for the given condition. But as I've come across, I think the 'for loop' loops over from the beginning. The example will make it much clearer.

numbers <- vector("numeric",length=4)
for (i in c(2,7,9,12)){
  numbers[[i]] <- i

Output looks like:


What I want is to create a vector that looks something like:
[1] 2 7 9 11

Is there a way to do so? Please help me out.

You are using i as both the value to be stored in the vector and the index of the position in the vector. That is, you are storing 7 in the 7th position. A version the works is this:

numbers <- vector("numeric",length=4)
Vec <- c(2,7,9,12)
for (i in seq_along(numbers)){
   numbers[i] <- Vec[i]
[1]  2  7  9 12

That is a roundabout way of doing

Vec <- c(2,7,9,12)
numbers <- Vec

This topic was automatically closed 7 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.