vendredi 26 novembre 2021

How to create a variable where the value is taken from another variable matching values of a vector

I'm new to R and I'm wondering if it is possible to create a variable whose values are taken from another variable if conditions are met.

I have a dataframe with a variable that is composed of strings of product's names. Ex.:

| Names                       | Price ...|
|-----------------------------|----------|
| milk                        | ...      |
| pizza with tomato           | ...      |
| tuna with olive and beans   | ...      |
| etc...                      | ...      |

What I would like to create is another variable that take as values names stored in a vector that match those in variable "Names"

Basically, if I have a vector:

x <- c("milk", "pizza", "tuna")

The code should look into the variable "Names" and if find a match in vector "x" then it takes that values and store it in a new variable called "tag" that should have as values "milk", "pizza", "tuna".

I hope I have been clear :)

I wasn't able to get what the answer for now.

Thanks in advance for your help!

Aucun commentaire:

Enregistrer un commentaire