【问题标题】:Join two column trivially in R在R中平凡地加入两列
【发布时间】:2020-06-19 14:51:44
【问题描述】:

我想连接两个表,一个包含旧产品和排名数据,第二个包含第一个表中某些产品的少数更新排名。

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

TIA :)

【问题讨论】:

    标签: r


    【解决方案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)
    
    

    【讨论】:

    • 兄弟在您的情况下,产品名称也已替换为序列号
    • @AliBaba 不,只是更改了顺序(仅在第一个示例中),数据与您想要的输出中的数据相同。你所说的序列号是行号。你可以忽略它们。
    • 序列号正在替换我的产品名称本身。 b 和 d 变成 1 和 2。
    • @AliBaba 这个很难复现,请提供你真实数据的sn-ps。您可以使用dput(head(table1))dput(head(table2)) 来做到这一点,并请发布两个调用的全部输出
    【解决方案2】:

    使用dplyr 并假设您的表是名为dfdf2 的data.frame:

    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
    

    【讨论】:

    • list2(...) 中的错误:找不到对象“Rank.y”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    相关资源
    最近更新 更多