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")
CodePudding user response:
Just match
the vector with key.
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
CodePudding user response:
You can try this:
out <- data.frame(
key = vec,
price = prod_table$price[match(vec, prod_table$key)]
)