Restrict range of continuous variable in a new variable

I want to create a clean age variable from original RIDAGEYR variable by restricting the range and filling the rest of values with NA.
This is wrong, but the idea is
nhanes$age = ifelse(nhanes$RIDAGEYR > 17 ,
nhanes$RIDAGEYR < 80 ,nhanes$RIDAGEYR)
How do I code this?
Help is appreciated.

Is this what you are after?

nhanes <- data.frame(RIDAGEYR = c(23,16,45,79,82,45))
nhanes$age = ifelse(nhanes$RIDAGEYR > 17 &
                    nhanes$RIDAGEYR < 80 ,nhanes$RIDAGEYR, NA)
nhanes
#>   RIDAGEYR age
#> 1       23  23
#> 2       16  NA
#> 3       45  45
#> 4       79  79
#> 5       82  NA
#> 6       45  45

Created on 2022-10-28 with reprex v2.0.2

1 Like

Yes, thank you so much for a prompt reply!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.