如果这个问题重复,我深表歉意。
有一个表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")
只使用关键字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