Set a conditional based on names in a column of a data set

Viewed 42

Let’s keep only the three counties with the most observations: Sonoma, Los Angeles, and Kern. Create a conditional called bigCounties that is TRUE if the variable county is any of these three counties. Remember that | is the or logical operator.

UPDATE

bigCounties <- isTRUE( CASchools$county == "Sonoma" | CASchools$county == "Los Angeles"|CASchools$county == "Kern")
summary(bigCounties)

OUTPUT:

   Mode   FALSE 
logical       1 

How do I get it to run through the entire dataset?

1 Answers

I think you should try %in%, e.g.,

CASchools$county %in% c("Sonoma", "Los Amgles", "Kern")

Otherwise, you should try

CASchools$county == "Sonoma"| CASchools$county == "Los Amgles"| CASchools$county =="Kern"

or (thank @akrun for the contribution)

Reduce(`|`, lapply(c("Sonoma", "Los Amgles", "Kern"), function(x) CASchools$county == x))

if you want to use |

Related