Search code examples
rif-statementconditional-statementsdelete-row

Delete rows when element matches a list


I have a dataset that looks like this:

Col1 Col2
0.7   AA
0.6   BBB
0.2   RR
0.8   TTT
0.0   SS

And another dataset that looks like that

List
BBB
RR
TTT

I want to remove rows from the first dataset when values from the second column does not match any of the names listed in the second dataset. Final product would look like this:

Col1 Col2
0.6   BBB
0.2   RR
0.8   TTT

I cannot find any easy way to run this in R. I tried different for and if loops but did not work. Anybody would know an easy solution?

Thank you!


Solution

  • Base R Solution:

    Dataset:

    df1=read.table(text="Col1 Col2
              0.7   AA
              0.6   BBB
              0.2   RR
              0.8   TTT
              0.0   SS",header=T)
     df2=read.table(text="List
               BBB
               RR
               TTT",header=T)
    

    Code:

    df1[df1$Col2 %in% df2$List,]
    

    Output:

      Col1 Col2
    2  0.6  BBB
    3  0.2   RR
    4  0.8  TTT