代码之家  ›  专栏  ›  技术社区  ›  Kra.P

如何通过将表的列与向量相匹配来展开表?

r
  •  0
  • Kra.P  · 技术社区  · 4 年前

    如果这个问题重复,我深表歉意。

    有一张桌子 prod_table 看起来像

          key price
    1 Printer   225
    2  Tablet   570
    3  Laptop  1120
    

    和矢量 vec

    [1] "Printer" "Laptop"  "Printer" "Tablet"  "Laptop" 
    

    我想要的是,匹配 prod_table$key 具有 vec 并展开此表。

    我试过了 prod_table[vec,] 但它没有起作用。

    所需输出如下

          key price
    1 Printer   225
    2  Laptop  1120
    3 Printer   225
    4  Tablet   570
    5  Laptop  1120
    

    这是一个可重复的例子。

    prod_table <- data.frame(
      key = c("Printer", "Tablet", "Laptop"),
      price = c(225, 570, 1120)
    )
    vec <- c("Printer", "Laptop", "Printer", "Tablet", "Laptop")
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   jay.sf    4 年前

    只是 match 带有键的矢量。

    prod_table[match(vec, prod_table$key), ]
    #         key price
    # 1   Printer   225
    # 3    Laptop  1120
    # 1.1 Printer   225
    # 2    Tablet   570
    # 3.1  Laptop  1120