0

I've been working with two df, one is the information recollected at the field and the other one it's like a diagnose table

Name<-c("Mario", "Pedro", "Julia", "Jazmin")
Weight<-c("110","50","67","80")
Pacients<- data.frame(Name, Weight)

 Pacients$Name $Weight
  <fct>         <fct>  
1 Mario         110    
2 Pedro         50     
3 Julia         67     
4 Jazmin        80  

Min_W<-c("45", "66", "76", "86", "101")
Max_W<-c("65","75","85","100","150")
Dx<-c("underw","inrange","preob","ob","morb")
W_Table<- data.frame(Min_W, Max_W, Dx)

W_Table$Min_W $Max_W $Dx    
  <fct>         <fct>  <fct>  
1 45            65     underw 
2 66            75     inrange
3 76            85     preob  
4 86            100    ob     
5 101           150    morb   

I've been trying with functions like mutate and ifelse but I keep having problems with returning just one value. The return should look something like this

Pacients_Dx$Name $Weight $Dx    
  <fct>            <fct>   <fct>  
1 Mario            110     morb   
2 Pedro            50      underw 
3 Julia            67      inrange
4 Jazmin           80      preob   
Martin Gal
  • 16,640
  • 5
  • 21
  • 39
Karen Lau
  • 35
  • 5
  • I think this question/answer is trying to solve the same problem. https://stackoverflow.com/questions/62912260/mutate-between-dates-from-external-lookup-table/ Did you check it? – Ronak Shah Jul 28 '20 at 00:28

2 Answers2

0

Try this.

w_table = rep("", max(as.numeric(W_Table$Max_W)))
for (i in 1:nrow(W_Table)) {
    for (j in W_Table[i, 1]:W_Table[i, 2]) {
        w_table[j] = W_Table[i, 3]
    }
}
Pacients$Dx = apply(Pacients, 1, 
                function(x) return(w_table[as.numeric(x[2])]))
Haci Duru
  • 456
  • 3
  • 9
0

in base R you could use findInterval:

transform(Pacients,Dx=with(W_Table,Dx[findInterval(Weight,as.numeric(c(Min_W[1],Max_W)))]))

    Name Weight      Dx
1  Mario    110    morb
2  Pedro     50  underw
3  Julia     67 inrange
4 Jazmin     80   preob
Onyambu
  • 67,392
  • 3
  • 24
  • 53