alinsoar
alinsoar

Reputation: 15813

Multiple conditions to select data of a frame in R

  1. Load this dataset (just start R, because it is already loaded by default):

    airquality

  2. Here, there are the columns Ozone Solar.R Wind Temp Month Day with 153 observations.

  3. I want to select a combination of the following:

    • Ozone > 50

    • Solar.R > 50

    • be defined (id est, drop the NAs).

I tried in R's console airquality[airquality$O > 50 && airquality$S > 50,], but the result is wrong.

Q: How to return the rows that have the good entries ?

Upvotes: 1

Views: 212

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193677

Here is an approach that uses subset (which is recommended only for interactive use, which is what you describe):

subset(airquality[complete.cases(airquality), ], Ozone > 50 & Solar.R > 50)

The idea here is to first drop the NAs with complete.cases, then to subset based on your conditions.


Sticking with [ notation, I suppose you could also do it in two steps, as below:

temp <- with(airquality, airquality[Ozone > 50 & Solar.R > 50, ])
temp[complete.cases(temp), ]

Upvotes: 6

Related Questions