Conditional Drop Panel data

Viewed 35

I'm working on a cross-section data set that looks like:

Id Year  Age 
1  2003  20  
1  2003  20  
1  2003  20  
2  2003  35   
2  2003  37   
2  2003  42  
3  2003  55   
3  2003  55   
3  2003  55   

To reduce measurement error in my sample due to Id assignment error I need to keep only individuals that have the same Age and drop if this condition is not attended.

The output I'm looking for is:

Id Year  Age 
1  2003  20  
1  2003  20  
1  2003  20  
3  2003  55   
3  2003  55   
3  2003  55   

Do you have any suggestions?

1 Answers

A base R option using ave + subset

subset(
  df,
  ave(Age,Id,Year,FUN = var)==0
)

gives

  Id Year Age
1  1 2003  20
2  1 2003  20
3  1 2003  20
7  3 2003  55
8  3 2003  55
9  3 2003  55

A possible dplyr option

df %>%
  group_by(Id, Year) %>%
  filter(n_distinct(Age) == 1) %>%
  ungroup()

gives

# A tibble: 6 x 3
     Id  Year   Age
  <int> <int> <int>
1     1  2003    20
2     1  2003    20
3     1  2003    20
4     3  2003    55
5     3  2003    55
6     3  2003    55
Related