Alternative to subset in R?

Viewed 90

I have for example 5 states and multiple cities for each state. I want to select only 1 city per state. I am trying this code:

country <- subset(country, country$state == "1" & country$city == "1" |  
                           country$state == "2" & country$city == "4" |
                           country$state == "3" & country$city == "3" | 
                           country$state == "4" & country$city == "2" |
                           country$state == "5" & country$city == "101")

Is there another way to do this? I find this code very ugly and unoptimal.

2 Answers

Store the values you want to keep in a data.frame

keep <- read.table(text="
state city
1 1
2 4
3 3
4 2
5 101", header=T)

Then merge to keep only matching rows

country  <- merge(country, keep)

subset uses an expression which is evaluated with envir = [the passed data.frame] as the argument in a call to eval. Thus, there is no need for country$

# simulate the data 
set.seed(1)
country <- data.frame(state = as.character(sample.int(10, 10000, TRUE)), 
                      city = as.character(sample.int(101, 10000, TRUE)),
                      stringsAsFactors = FALSE)

# your way
r1 <- subset(country, country$state == "1" & country$city == "1" |  
                      country$state == "2" & country$city == "4" |
                      country$state == "3" & country$city == "3" | 
                      country$state == "4" & country$city == "2" |
                      country$state == "5" & country$city == "101")

# using expressions
r2 <- subset(country, state == "1" & city == "1" |  
                      state == "2" & city == "4" |
                      state == "3" & city == "3" | 
                      state == "4" & city == "2" |
                      state == "5" & city == "101")

# gives the same
all.equal(r1, r2)
#R> [1] TRUE
Related