如何匹配不同大小的变量?

时间:2019-01-20 02:56:51

标签: r match

假设我有以下代码:

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

运行此命令时,将产生以下两个数据帧:

  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

我想在另一个数据框中相互匹配重复分配编号,同时从两个没有重复分配值的数据框中删除值。所需的输出如下:

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

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您正在寻找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

reprex package(v0.2.1)于2019-01-19创建