EconGradKI
EconGradKI

Reputation: 67

Subsetting all observations except two in R

I have a variable called Country, with the following observations:

"AUS","AUT","BEL","BRA","BGR","CAN","CHN","CYP","CZE","DNK","EST","FIN","FRA","DEU", "GRC","HUN","IND","IDN","IRL","ITA","JPN","KOR","LVA", "LTU","LUX","MLT","MEX","NLD", "POL","PRT","ROU","RUS","SVK","SVN","ESP","SWE","TWN","TUR","GBR","USA"

I want to subset so that all observations where Country == LUX|MLT are dropped.

I tried (the rather messy):

mydata <- subset(mydata, Country == c("AUS","AUT","BEL","BRA","BGR","CAN","CHN","CYP","CZE","DNK","EST","FIN","FRA","DEU", "GRC","HUN","IND","IDN","IRL","ITA","JPN","KOR","LVA", "LTU","MEX","NLD", "POL","PRT","ROU","RUS","SVK","SVN","ESP","SWE","TWN","TUR","GBR","USA"))) 

But unfortunately I got the error message:

Warning messages:
1: In is.na(e1) | is.na(e2) :
  longer object length is not a multiple of shorter object length
2: In `==.default`(Country, c("AUS", "AUT", "BEL", "BRA", "BGR", "CAN",:
  longer object length is not a multiple of shorter object length

Upvotes: 0

Views: 93

Answers (2)

SabDeM
SabDeM

Reputation: 7190

here is my solution. I use grep function.

data <- Country[-grep("LUX|MLT", Country)]

Upvotes: 3

sgibb
sgibb

Reputation: 25736

Try using %in% instead of ==. == assumes that both sides are of an equal length (or one side could be recycled).

mydata <- subset(mydata, Country %in% c("AUS",...,"USA")))

Upvotes: 1

Related Questions