Robert Robert - 1 month ago 4
R Question

How to use the subset function to search for a special character in R

I am trying to use the subset function to pick out certain lines of a data frame which contain the symbols * or +. I would like to put these entire lines of my data frame into a new data frame. I think that subset will be the best way to do this.

Below is my attempt:

nba <- read.csv('nba.csv',header=FALSE)

nba
two <- grep('\\Q*\\E',nba$V2)
one <- grep('\\Q+\\E',nba$V2)

both <- c(one,two)

allstar <- subset.data.frame(nba, both)


If anyone can give me advice thank you. I apologize if I have any formating mistakes. This is my first time on this website.

Thank you.

Note: I am working in R studio

Answer

subset takes logical values for subset argument. Use grepl ("l" for "logical") instead:

two <- grepl('\\Q*\\E',nba$V2)
one <- grepl('\\Q+\\E',nba$V2)

both <- one | two  ## logical "or" operation

allstar <-  subset.data.frame(nba, both)

Note, two, one and both have length nrow(nba).