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!
To iterate over items of a vector in R programming, use R For Loop. For every next iteration, we have access to next element inside the for loop block.
You can create a vector both by enclosing the elements in square brackets like v=[1 2 3 4 5] or using commas, like v=[1,2,3,4,5]. They mean the very same: a vector (matrix) of 1 row and 5 columns. It is up to you.
Use the vector() Function to Create an Empty Vector in R The vector() function in R is used to create a vector of the specified length and type specified by length and mode . The mode by default is logical but can be changed to numeric, character, or even to list or some expression.
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.
x=c()
x[1] = 3
for (i in 2:9) {
x[i]=2*x[i-1]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With