lundi 7 décembre 2020

Does a value falls between two values in another table? if so rename it based on that

I have two table and I want to see if a value from one table 'newtab' falls between the low and high values in another table 'vals'. Then assign the 'animal' associated with that range to the name in the 'newtab'.

The catch is some values in the from 'newtab' are not in the 'vals' table, so just assign that an "NA", and other are in there twice, so just assign that based any of the ranges it fall in between.

vals
low high animal
100 103  dog
107 114  cat
114 120  fish
116 123  goat

newtab
name value
NA   102
NA   105
NA   115
NA   119

I want it to look like this:

  newtab
    name value
    dog  102
    NA   105
    fish 115
    fish 119

or

   newtab
    name value
    dog  102
    NA   105
    fish 115
    goat 119  

either one is fine (the last name can be assigned to fish or goat This is what i tried but it doe not work...?

for (i in 1:length(newtab[,2])){
    for (j in i:length(vals[,2])){
        ifelse(((newtab[i,2] >vals[j,1])==TRUE & (newtab[i,2]<vals[j,2])==TRUE)==TRUE,newtab[i,1]<-vals[j,3], NA)
    }   
}

Thanks for your help!

Aucun commentaire:

Enregistrer un commentaire