AP38
AP38

Reputation: 169

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!

Upvotes: 0

Views: 69

Answers (2)

Bram Van Rensbergen
Bram Van Rensbergen

Reputation: 387

Using data.table:

dt <- data.table(Col1 = c(0.7, 0.6, 0.2, 0.8, 0), Col2 = c("AA", "BBB", "RR", "TTT", "SS"))
myList <- list("BBB", "RR", "TTT")

dt[Col2 %in% myList]

Gives you:

   Col1 Col2
1:  0.6  BBB
2:  0.2   RR
3:  0.8  TTT

Upvotes: 1

Saurabh Chauhan
Saurabh Chauhan

Reputation: 3221

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

Upvotes: 2

Related Questions