lundi 26 juin 2017

ifelse function - replacement has length zero R

I have a dataset BBB which is a list and contains (0,1,2) values and Xx 37232 obs. of 1 variable.

head(Xx)
Xx
1           NA
2 0.0006458981
3 0.0014977347
4 0.0021436328
5 0.0018066425



head(BBB)
$`1`
[1] 1 2 0 0 0 0
$`2`
[1] 1 2 0

Then I made a rule to get values which according to their positions I am going to subset Xx later

B<-rep(NA,(length(BBB)-2))
for(i in 1:(length(BBB)-2)){B[i]<-length(BBB[[i]])+as.numeric(which(BBB[[i+1]]==1))}

S<-rep(NA,(length(BBB)-2))
for(i in 1:(length(BBB)-2)){S[i]<-length(BBB[[i]])+as.numeric(which(BBB[[i+1]]==2))}
B<-as.data.frame(B)
S<-as.data.frame(S)

So the subset works like following: Xx[B[5,]:S[5,],]

[1] -0.008050324 -0.007825664 -0.008471562 -0.008986408

Now I want to make a new rule to save the first value of each subset of Xx which is higher or equal to 0.004

For example:

which(Xx[B[13,]:S[13,],]>=.0001)
[1] 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
head(which(Xx[B[13,]:S[13,],]>=.0001),n=1)
[1] 277

So I wrote the following code:

SSS<-rep(NA,length(Xx))
for(i in 2:length(Yy)){SSS[i]<-ifelse(head(which(Xx[B[i,]:S[i,],]>=.004),n=1),
                                  Xx[head(which(Xx[B[i,]:S[i,],]>=.004),n=1),],
                                  tail(which(Xx[B[i,]:S[i,],]>=.004),n=1))}

But when applying it I am getting the following error:

Error in SSS[i] <- ifelse(head(which(Xx[B[i, ]:S[i, ], ] >= : replacement has length zero

Why I am getting this massage and what is wrong in my code? and any suggestion on how can I solve it?

Aucun commentaire:

Enregistrer un commentaire