Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a vector using a for loop

Tags:

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!

like image 715
user1990538 Avatar asked Jan 18 '13 13:01

user1990538


People also ask

How do I loop a vector in R?

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.

How do you create a vector in Matlab?

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.

How do you create an empty vector of length n in r?

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.


2 Answers

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.

like image 70
Jack Aidley Avatar answered Sep 28 '22 22:09

Jack Aidley


x=c()
x[1] = 3
for (i in 2:9) { 
    x[i]=2*x[i-1]
}
like image 22
Tomas Avatar answered Sep 28 '22 23:09

Tomas