L. Smith - 1 year ago 75
R Question

# Making a looping statement that populates a vector?

I've tried a couple ways of doing this problem but am having trouble with how to write it. I think I did the first three steps correctly, but now I have to fill the vector

`z`
with numbers from
`y`
that are divisible by four, not divisible by three, and have an odd number of digits. I know that I'm using the
`print`
function in the wrong way, I'm just at a loss on what else to use ...
This is different from that other question because I'm not using a while loop.

``````#Step 1: Generate 1,000,000 random, uniformly distributed numbers between 0
#and 1,000,000,000, and name as a vector x. With a seed of 1.
set.seed(1)
x=runif(1000000, min=0, max=1000000000)

#Step 2: Generate a rounded version of x with the name y
y=round(x,digits=0)

#Step 3: Empty vector named z
z=vector("numeric",length=0)

#Step 4: Create for loop that populates z vector with the numbers from y that are divisible by
#4, not divisible by 3, with an odd number of digits.
for(i in y) {
if(i%%4==0 && i%%3!=0 && nchar(i,type="chars",allowNA=FALSE,keepNA=NA)%%2!=0){
print(z,i)
}
}
``````

You've got the vector created before the loop, that's a good start. Now, inside your loop, you need to populate that vector. To do so, you've currently got `print(z,i)`, which won't really do too much. What you need to to change the vector itself:
``````z <- c( z, i )
Should work for you (just replace that `print` line in your loop).
What's happening here is that we're taking the existing `z` vector, binding `i` to the end of it, and making that new vector `z` again. So every time a value is added, the vector gets a little longer, such that you'll end up with a complete vector.