How to make a vector using a for loop

2019-02-06 07:01发布

问题:

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!

回答1:

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.



回答2:

x=c()
x[1] = 3
for (i in 2:9) { 
    x[i]=2*x[i-1]
}


回答3:

Really, folks. Stick with the solution hiding in Arun's comment.

Rgames> 3*2^(0:20)
 [1]       3       6      12      24      48      96     192     384     768
[10]    1536    3072    6144   12288   24576   49152   98304  196608  393216
[19]  786432 1572864 3145728