0

I have a long dataset in which each participant should have 9 measurements, but they all have more than 9. These measurements need to be within specific brackets of the Weeks variable.

  • Measurement 1 should be < 12 weeks (ideal 10)
  • Measurement 2 should be >=12 and <25 weeks (ideal 16)
  • Measurement 3 should be >=25 and <28 weeks (ideal 25)
  • Measurement 4 should be >=28 and <31 weeks (ideal 28)
  • Measurement 5 should be >=31 and <34 weeks (ideal 31)
  • Measurement 6 should be >=34 and <36 weeks (ideal 34)
  • Measurement 7 should be >=36 and <38 weeks (ideal 36)
  • Measurement 8 should be >=38 and <40 weeks (ideal 38)
  • Measurement 9 should be >=40 weeks (ideal 40)

If there is more than one measurement in the bracket per participant, I would like the measurement closest to the ideal number of weeks (indicated above in parentheses) to remain, and the rest of the rows to be removed.

This an example of my data:

ID <- c(1,1,1,1,1,1,1,1,1,1,
    2,2,2,2,2,2,2,2,2,2,2,2,2)
Weeks <- c(11,16,25,28,31,34,35,36,38,40,
       6,12,13,26,29,31,32,33,34,36,38,40,41)
Measurement <- c(120,160,170,200,120,40,89,70,63,44,
             90,92,93,94,95,96,97,100,100, 120,
             110, 100, 130)
df1 <- data.frame(ID, Weeks, Measurement)

DF1

This is what I would like it to look like, with rows 7, 12, 17, 18, and 23 removed.

DF2

Thank you for any help!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.