Search code examples
rtidyversetidyrtibble

Adding a newcolumn using tidyverse in R?


I have two datasets data1 and data2 which is given in the form below

    > data1 

        x      y z
        apple  3 3
        banana 4 3
        mango  1 1
        pear   2 1
        lemon  3 1

 > data2=
    X  
    mango 
    pear 
    lemon 

what I'm trying to achieve is in a similar example as below, that is when the data2 is present data1 a column should be created with type as good and other columns should be named as bad. I have created an example format below. I'm trying to do this in R preferably in tidyverse library or any other. Any suggestions on how to approach this will be appreciated.

x      y z  type
apple  3 3  bad
banana 4 3  bad
mango  1 1  good
pear   2 1  good
lemon  3 1  good

Solution

  • The key is the %in% operator, whether you do this in tidyverse or base R.

    data1 %>% mutate(type = (x %in% data2$X))