Index for one line -> same index for several lines

Hey there,

I have the following question:

In one column I have 150 rows with product names (all different). I have assigned an index from 0 to 2 in another column (50 rows/products per index). In a second table I have the same product names, but they are contained several times. Now I want to assign the same index from table 1 to the same product names in the second table. I don't know how to assign the same index if the product name is contained several times.

Thank you very much for your help.
Paula

Hi Paula,

It would help if you could provide a representative example (reprex). You can use this guide: FAQ: What's a reproducible example (`reprex`) and how do I create one?

This will help us assist you better.

See the FAQ: How to do a minimal reproducible example reprex for beginners for possibly more useful answers.

Creating an index of product names shared by two data frames is doable, but contortions may be required if both datasets are not in tidy format. In particular, to use the following, make sure that the first table or its copy has only the two columns, product and id or you'll carry over data you may not wish to.

set.seed(137)
df1 <- data.frame(product = sample(LETTERS,25),
                  id = sample(1:25,25))
set.seed(137)
df2 <- data.frame(product = sample(LETTERS,50, replace = TRUE))

head(df1)
#>   product id
#> 1       B  1
#> 2       H 16
#> 3       O 23
#> 4       F  3
#> 5       X 22
#> 6       G 24
head(df2)
#>   product
#> 1       B
#> 2       H
#> 3       O
#> 4       F
#> 5       O
#> 6       G
head(dplyr::left_join(df2,df1,by="product"))
#>   product id
#> 1       B  1
#> 2       H 16
#> 3       O 23
#> 4       F  3
#> 5       O 23
#> 6       G 24

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.