Ramiro Guzmán
Ramiro Guzmán

Reputation: 45

filter information in a dataframe according multiple variables in R

the function 'filter' in R allows to filter some information, usually, someone wants to filter one or two values, however, I want to filter some values according some variables (in my case two) of another data frame. I type an example about I have and I need.

Main data frame:

df_root<-data.frame('id'=c('1a','1a','2a','2a'),
                    'zone'=c('II', 'I', 'I', 'II'),
                    'date'=c(1,6,1,5))

Alternative data frame:

df_alternative<-data.frame('id'=c('1a', '2a'),
                           'date'=c(6,5))

So, I need to filter the information from the second data frame into the first, according the variables df_alternative$id and df_alternative$date. The result must be as following.

df_root_filtered:

| id   | zone | date|
| ---- | ---- |-----|
| 1a   | I    | 6   |
| 2a   | II   | 5   |

Thanks for your help

Upvotes: 0

Views: 35

Answers (1)

seaFan
seaFan

Reputation: 116

It sound like you want a left (or right) join, so you want all rows from df_root that have corresponding rows in df_alternative, correct? If so, you can use the merge function.

merged_tables <- merge(df_root, df_alternative, all.x = FALSE, all.y = TRUE)

Upvotes: 1

Related Questions