0

I want to subset a data frame by age group.

Only those obs where:

age > 35 and age < 80

My attempts didn't give what I wanted.

It gave me rows below 35 and above 80 for age.

subset(data,age > 35 & age < 80,select = myvar)

I tried &&, but that didn't work either.

Does this have to be done in two steps?

Grant Miller
  • 27,532
  • 16
  • 147
  • 165
user242509
  • 11
  • 1
  • 3
  • 1
    Please make this question *reproducible*. This includes sample code sample data (e.g., `dput(head(x))`) and expected output. Refs: https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info. – r2evans Sep 20 '18 at 23:44
  • Provided that `data` contains columns `age`, `myvar` with values in the expected range, I cannot see why that code example would not work as expected. – neilfws Sep 20 '18 at 23:46
  • 1
    This works: `subset(data.frame(age=c(1,30,50,80,100), myvar=letters[1:5]), age > 35 & age < 80, select = myvar)` (which is just your subsetting/selecting with known data). – r2evans Sep 20 '18 at 23:47
  • Yes, I tried this on a simple dataset and it works! Not sure whats wrong with my dataset, it's from nhanes. If I figure it out, I'll post the problem, thanks Bob I thought it was my code. – user242509 Sep 21 '18 at 15:31
  • Well, the problem was the age variable is character not numeric. I should have noticed when one of the entries was "80 years of age and older", but I'm new to this type of dataset. Sorry for the confusion. Bob – user242509 Sep 21 '18 at 16:31

1 Answers1

0

You don't need to use subset() try something like this:

person <- c("John", "Jane", "Bill", "Betty", "Cindy")
age <- c(10, 40, 50, 90, 100)
data <- data.frame(person, age)
age35_80 <- data[data$age > 35 & data$age < 80,]

Only need to use a single & to vectorize.

sshemtov
  • 13
  • 5