mle mle - 3 years ago 81
R Question

Comparing variables with values in another dataframe and replace them with another value

I have a Data.Frame with:

Height <- c(169,176,173,172,176,158,168,162,178)


and another with reference heights and weights.

heights_f <- c(144.8,147.3,149.9,152.4,154.9,157.5,160,162.6,165.1,167.6,170.2,172.7,175.3,177.8,180.3,182.9,185.4,188,190.5,193,195.6)
weights_f <- c(38.6,40.9,43.1,45.4,47.7,49.9,52.2,54.5,56.8,59,61.3,63.6,65.8,68.1,70.4,72.6,74.9,77.2,79.5,81.7,84)
weightfactor_f <- data.frame(heights_f, weights_f)


I now need to match the values of the heights from the first data.frame with the height reference in the second one that's the most fitting and to give me the correspondent reference weight.

I haven't yet had any success, as I haven't been able to find anything about matching values that are not exactly the same.

Answer Source

If I understand your goal, instead of taking the nearest value, consider interpolating through the approx function. For instance:

approx(weightfactor_f$heights_f,weightfactor_f$weights_f,xout=Height)$y
#[1] 60.23846 66.44400 63.85385 62.95600 66.44400 50.36000 59.35385 53.96923
#[9] 68.28400
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download