-1

I am using square brackets to select rows of data in a data frame based on logical operators. For example, if I have a data frame

df = data.frame(Letter = rep(c("A", "B", "C", "D", "E"), 10), Number = rep(c(1:25), 4))

and I want to select rows that contain the letters A, B, or C I use the code

df = df[df$Letter == "A" | df$Letter == "B" | df$Letter == "C",]

I'm wondering if there is a way to condense this, something along the lines of

df = df[df$Letter == c("A", "B", "C"),]

or maybe

df = df[df$Letter == "A" | "B" | "C",]

neither of which work, but basically I'm looking for a shorter, easier way to list several logical operators.

I would prefer to do it with square brackets rather than subset() or some other function but if it really isn't possible with square brackets then I would be open to other ideas

C. Denney
  • 577
  • 4
  • 16

2 Answers2

1

You could do this:

df <- df[df$Letter %in% c("A", "B", "C"),]
Oriol Mirosa
  • 2,756
  • 1
  • 13
  • 15
0

For these instances I use the dplyr package.

library(dplyr)
new.df <- df %>% 
filter(Letter %in% c("A", "B", "C"))

I hope that helps,

cheers!

PS: dplyr cheat sheet is here

Joram
  • 139
  • 5
  • 11