1

我想加入两个表,一个是旧产品和排名数据,第二个是第一个表中某些产品的更新排名很少。

EG:(说)

table 1-

Product    Rank 
a           32     
b           21
c           14
d           36
e            1

table 2-

Product   Rank
b          7
d          8

我希望输出表看起来像:

Product    Rank
a           32
b            7
c           14
d            8
e            1

蒂亚:)

4

2 回答 2

1

使用dplyr并假设您的表是名为dfand的 data.frames df2

df %>% 
  left_join(df2, by="Product") %>%
  mutate(Rank=coalesce(Rank.y, Rank.x)) %>%
  select(-Rank.x, -Rank.y)

产量

# A tibble: 5 x 2
  Product  Rank
  <chr>   <dbl>
1 a          32
2 b           7
3 c          14
4 d           8
5 e           1
于 2020-06-19T15:09:31.350 回答
1

使用基础 R 的一种方法:

rbind(table1[!table1$Product %in% table2$Product, ], table2)
#>    Product Rank
#> 1        a   32
#> 3        c   14
#> 5        e    1
#> 11       b    7
#> 2        d    8

或者,通过分配:

table1[table1$Product %in% table2$Product, ] <- table2

table1
#>   Product Rank
#> 1       a   32
#> 2       b    7
#> 3       c   14
#> 4       d    8
#> 5       e    1

数据

table1 <- read.table(text =
"Product    Rank 
a           32     
b           21
c           14
d           36
e            1", header = TRUE)

table2 <- read.table(text =
                       "Product   Rank
b          7
d          8", header = TRUE)

于 2020-06-19T15:13:00.177 回答