I apologize if this question is duplicated.
There is a table prod_table looks like
key price
1 Printer 225
2 Tablet 570
3 Laptop 1120
And vector vec
[1] "Printer" "Laptop" "Printer" "Tablet" "Laptop"
What I want is, match prod_table$key with vec and expand this table.
I tried prod_table[vec,] but it did not work.
Desired output looks like
key price
1 Printer 225
2 Laptop 1120
3 Printer 225
4 Tablet 570
5 Laptop 1120
Here is reproducible example.
prod_table <- data.frame(
key = c("Printer", "Tablet", "Laptop"),
price = c(225, 570, 1120)
)
vec <- c("Printer", "Laptop", "Printer", "Tablet", "Laptop")
>Solution :
The problem with match is that it only matches once. Put it in an sapply.
prod_table[sapply(vec, match, prod_table$key), ]
# key price
# 1 Printer 225
# 3 Laptop 1120
# 1.1 Printer 225
# 2 Tablet 570
# 3.1 Laptop 1120