lundi 18 février 2019

R: Problems with an "if" condition

I am dealing with the following problem, I have two vectors namely:

index1<-c(10 ,11 ,12 ,13 ,14 ,15 ,16 ,17 ,18 ,19 ,20 ,21, 22, 23, 24, 25, 26, 27, 28, 29)

index2<-c(17 ,18, 19, 20 ,22 ,23, 24, 25, 26, 27, 28, 29, 30 ,31 ,32, 33 ,42, 43, 44,45, 46 ,47 ,48, 49, 50, 51, 52 ,53, 54 ,55, 56)

I want to keep all the components index2[j] that can be written as 2*index1[i]+k where k=0,1,2,3. for some i in 1:length(index1),j in 1:length(index2)

This is, for instance the first component of index2 is 17, and this cannot be written as 2*index1[i]+k so this first component should be deleted (or replaced with a NA). I am having a hard time trying to figure out how to do that, I've tried to do a loop but without success.

for(j in 1:length(index2)){
  for(i in 1:length(index1)){
    for(k in 0:3){
if (index2[j]!=(2*index1[i]+k)){index2[j]=NA}else{index2[j]=index2[j]}}}}

Any help will be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire