0

Suppose I have the following code:

color1 <- c("red", "blue", "yellow", "orange", "green", "brown")
assignment <- c(1,2,3,4,9,13)
color_df <- as.data.frame(color1)
color_df$assignment <- assignment

sport1 <- c("basketball", "hockey", "baseball", "soccer", "tennis", "football", "volleyball")
assignment <- c(4,3,6,1,5,7,2)
sport_df <- as.data.frame(sport1)
sport_df$assignment <- assignment

When this is run, it yields the following two data frames:

  color1 assignment
1    red          1
2   blue          2
3 yellow          3
4 orange          4
5  green          9
6  brown         13

      sport1 assignment
1 basketball          4
2     hockey          3
3   baseball          6
4     soccer          1
5     tennis          5
6   football          7
7 volleyball          2

I want to match the recurring assignment numbers to each other in another data frame, while removing the values from both data frames that do not have recurring assignment values. The desired output is below:

  color1     sport1 assignment
1    red     soccer          1
2   blue volleyball          2
3 yellow     hockey          3
4 orange basketball          4

How would I do this?

Paul Ibrahim
  • 413
  • 1
  • 3
  • 14

1 Answers1

1

You're looking for merge()

color1 <- c("red", "blue", "yellow", "orange", "green", "brown")
assignment <- c(1,2,3,4,9,13)
color_df <- as.data.frame(color1)
color_df$assignment <- assignment

sport1 <- c("basketball", "hockey", "baseball", "soccer", "tennis", "football", "volleyball")
assignment <- c(4,3,6,1,5,7,2)
sport_df <- as.data.frame(sport1)
sport_df$assignment <- assignment

merge(color_df, sport_df, by = "assignment")
#>   assignment color1     sport1
#> 1          1    red     soccer
#> 2          2   blue volleyball
#> 3          3 yellow     hockey
#> 4          4 orange basketball

Created on 2019-01-19 by the reprex package (v0.2.1)

dylanjm
  • 2,011
  • 9
  • 21