How to make a vector using a for loop

user1990538 picture user1990538 · Jan 18, 2013 · Viewed 90.8k times · Source

I'm very new to R (and programming in general) and I've been stuck on this (probably very easy) question for a few days...

How would one make the vector 3 6 12 24 48 96 192 384 768 with a for loop?

All I've managed to come up with so far is something along the lines of:

x=numeric()
for (i in 1:8) (x=2*i[-1])

However, that doesn't work. I think one of the main problems is that I don't understand how to index numbers in a sequence.

If anyone could point me in the right direction that would be such a great help!

Answer

Jack Aidley picture Jack Aidley · Jan 18, 2013

Okay, the first thing you need to know is how to append things to a vector. Easily enough the function you want is append:

x <- c(1, 2)
x <- append(x, 3)

will make the vector x contain (1, 2, 3) just as if you'd done x <- (1, 2, 3). The next thing you need to realise is that each member of your target vector is double the one before, this is easy to do in a for loop

n <- 1
for (i in 1:8)
{
    n <- n*2
}

will have n double up each loop. Obviously you can use it in its doubled, or not-yet-doubled form by placing your other statements before or after the n <- n*2 statement.

Hopefully you can put these two things together to make the loop you want.