问题
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