How to compare values with a reference table in R?

◇◆丶佛笑我妖孽 提交于 2021-02-10 15:05:23

问题


I have following 2 dataframes. The 'ddf' has age and wt values of group while 'refdf' is reference table for lower and upper limit of wt for different ages.

ddf =  read.csv(text="
                    age, wt
                    10,26
                    9,21
                    8,28
                    6,16
                    7,20
                    11,24",header=T)

refdf =  read.csv(text="
                    age,lower,upper
                    5, 10, 14
                    6, 11, 13
                    7, 13, 15
                    8, 14, 18
                    9, 16, 21
                    10, 17, 22
                    11, 19, 25
                    12, 22, 29",header=T)

I need to have another column called 'result' in ddf which should have a value of -1,1 or 0 depending on the wt being <= lower, >=upper or between lower & upper of refdf for the corresponding age value.

I tried following code but it does not work:

ddf$result = ifelse(refdf[age<=lower,],-1, ifelse(refdf[age>=upper,],1,0))
Error in `[.data.frame`(refdf, age <= lower, ) : object 'lower' not found

How can I accompalish this? Thanks for your help.


回答1:


You can assomplish this by first finding the correct category with match, then doing the comparisons and converting them to numeric values.

m <- match(ddf$age, refdf$age)
ddf$result <- (refdf$lower[m] > ddf$wt) *(-1) + 
    (ddf$wt > refdf$upper[m])*1

# 1  10 26      1
# 2   9 21      1
# 3   8 28      1
# 4   6 16      1
# 5   7 20      1
# 6  12 18     -1
# 7  11 24      0

(I added in an underweight individual) You can take out the = part of the inequalities if you want weights on the boundaries to be in the OK zone.



来源:https://stackoverflow.com/questions/23925702/how-to-compare-values-with-a-reference-table-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!