Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to expand table, by matching table's column against a vector?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading