2

私は基本的に NA と数値のベクトルを作成しようとしていますが、非常に特定の順序で作成しています。これまでのコードは次のとおりです。

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
}

したがって、私のベクトルは次のようになります (NA、NA、1、1、1、NA、NA、6、6、6 など)。ただし、これをこの形式で保存することはできないため、後でマトリックスで呼び出すことができます。助言がありますか?何もないベクトルを作成してからループに入れようとしましたが、それも役に立ちませんでした。

リズ統計学生

4

2 に答える 2

3

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)
于 2012-06-27T23:42:30.033 に答える
2

を呼び出すのではなく、ベクトルを何かに割り当てる必要がありますprint。そうしないと、標準出力に出力されます。

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
> 
于 2012-06-27T23:03:22.297 に答える