简体   繁体   中英

How to make a vector using a for loop

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!

x=c()
x[1] = 3
for (i in 2:9) { 
    x[i]=2*x[i-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.

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

sapply(1:9, function(i) 3*2**(i-1) )

You could, if you know python use the package reticulate to do it which would be much easier than in r (which is how I did a similar task).

If you don't have the package then do:

install.packages('reticulate')

Then if you do, you could do

library('reticulate')

py_run_string('vector = [n*2 for n in range(1, 9, 1)']
#Then you can call the vector by:

print(py$vector)

#And do whatever you want with it.  

I know that this was more python than r and it was made a bit more complicated then it could have been but for me personally, I found python more easier than r for manipulating vectors (or lists, the python equivalent). I hope that this answers your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM