tnabdb
tnabdb

Reputation: 547

How to use dplyr filter to select observations satisfying two conditions from another data frame?

My data frame looks like

state    year  taxrev
Alabama  1970  209297
Alabama  1971  239502
...
Alabama  1981  239502
Alaska   1970  209701
Alaska   1971  230980
...
Alaska   1981  230982
...

I also have a reference data frame like this

state   year 
Alabama  1975
Alaska   1977
Illinois 1973
...

How do I get the taxrev for the state-year pairs in the reference data frame using dplyr (I know how to do it with base R)?

Upvotes: 1

Views: 1364

Answers (3)

user2100721
user2100721

Reputation: 3587

You don't need to filter. Use match_df function of plyr package.

See this example

Data

my_data <- data.frame(state=c(rep("Alabama",3),rep("Alaska",3)),year=c(1970,1971,1975,1977,1963,1975),taxrev=c(209297,239502,254663,209701,230982,26789))
ref_data <- data.frame(state=c("Alabama","Alaska"),year=c(1975,1977))

R Code

match_df(my_data,ref_data)

Output

    state year taxrev
3 Alabama 1975 254663
4  Alaska 1977 209701

Upvotes: 1

boshek
boshek

Reputation: 4406

Also this would probably work, though untested because of no reproducible data:

reference_df %>%
 filter(year %in% taxrev_df$year)

Upvotes: 0

Jacob
Jacob

Reputation: 3557

Assuming the columns are consistently named as in your example and your 2 data frames are called taxrev_df and reference_df respectively then:

reference_df <- left_join(reference_df, taxrev_df)

Upvotes: 0

Related Questions