Elizabeth Giles
Elizabeth Giles

Reputation: 21

Create vector from loop in R

I'm basically trying to create a vector of NA's and numbers but in a very particular order. Here's the code I have so far:

x<-rep(rep(2:1,c(2,3)),40)
dummy=1
for (i in 0:length(x))
{ ifelse(x[i+1]==2, print(NA), print(dummy))
 if(i %% 5 == 0) dummy=i+1
}

So my vector should look as follows (NA, NA, 1, 1, 1, NA, NA, 6, 6, 6, etc). However I cannot save this in this format so I can call it later in a matrix. Any suggestions? I have tried creating a vector of nothing and then filling it in the loop but that has worked with no avail either.

Liz Statistics Student

Upvotes: 2

Views: 7651

Answers (2)

Seth
Seth

Reputation: 4795

After alot of stubbornness on my part I have learned to vectorize these things completely, not sure if this helps in your particular situation but I would write:

x<-rep(rep(2:1,c(2,3)),40)

get the lead of your x with:

leadx=c(x[-1],NA)

write the numbers that you would get if there were no NAs

filler=rep(5*0:7+1,each=5)

get a vector with the right size filled in with NAs

y=rep(NA,length(x))

plug in the values of the filler into your NA vector

y[which(leadx!=2)]=filler[which(leadx!=2)]

check it out with:

head(y)

> [1] NA  1  1  1 NA NA  6  6  6 NA

Vectorized stuff tends to be faster than for loops and if statements. Good luck!

Edit: You can do it all in one line with:

y=ifelse(c(x[-1],NA)==2,NA,1)*rep(5*0:7+1,each=5)

Upvotes: 3

Justin
Justin

Reputation: 43245

You need to assign your vector to something, rather than calling print, otherwise it will print to standard out.

out <- vector(length=length(x))

for (i in 0:length(x)) { 
  out[i] <- ifelse(x[i+1]==2, NA, dummy)
  if(i %% 5 == 0) dummy=i+1
}

> head(out, 10)
 [1] NA  1  1  1 NA NA  6  6  6 NA
> 

Upvotes: 2

Related Questions