Mosby83
Mosby83

Reputation: 1

R: "Which" function gives unexpected (and unwanted) results when using a comparison (>=)

I do not understand why the "which" function is not giving the right result here. I just want to select airports in Pennsylvania with more than 5,000 commercial service operations, and the result always contains a number of commercial service operations inferior to 5,000, as seen below.

I have read several questions indicating issues with "which", but I have seen none of that sort, and I have not had this issue before using this function.

Test4<-Airports[which(Airports$LAN_FA_TY=="AIRPORT" & 
                      Airports$STATE_NAME=="PENNSYLVANIA" & 
                      Airports$COMM_SERV>= "5000")
                , ]
Test4$COMM_SERV
# [1] 77680    73    71

Upvotes: 0

Views: 85

Answers (1)

talat
talat

Reputation: 70296

In this code snippet Airports$COMM_SERV>= "5000" you're using " " around a numeric value (the 5000) which turns the number into a character and hence you can no longer use mathematical operations like >= with that character. Just remove the "" and it should work as expected. (The use of comparison operators for character objects is allowed and meaningful. See ?'>='. It's just that the results may not be what were expected.)

Looking at your code, you could also profit from using with() to reduce the typing and improve readability:

with(Airports, Airports[which(LAN_FA_TY == "AIRPORT" & STATE_NAME == "PENNSYLVANIA" & COMM_SERV >= 5000),])

Upvotes: 3

Related Questions