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

  • 本文关键字:向量 扩展 何通过 r
  • 更新时间 :
  • 英文 :


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

有一个表prod_table看起来像

key price
1 Printer   225
2  Tablet   570
3  Laptop  1120

和矢量vec

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

我想要的是,将prod_table$keyvec匹配并展开此表。

我试过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")

只使用关键字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

最新更新