Subset character vector in R

Viewed 507

I know this is a super easy question but I really don't know what the best (most common) way in R is. I have a character-vector:

> dataframes
[1] "saga/dataframes/isce.log"                          "saga/dataframes/no_filter.csv"                    
[3] "saga/dataframes/sig0.9_iter100_viter50_nb_cv0.csv" "saga/dataframes/sig0.9_iter20_viter50_nb_cv0.csv" 

And what I want are the entries where no isce.log is in the element. So actually the 2nd to 4th. There are so many options in R to work with character-vector that I'm super confused. Is this a case for subset or maybe for dplyr's filter or str_subset...?

3 Answers

Using str_subset :

stringr::str_subset(dataframes, "isce.log", negate = TRUE)

#[1] "saga/dataframes/no_filter.csv" 
#[2] "saga/dataframes/sig0.9_iter100_viter50_nb_cv0.csv"
#[3] "saga/dataframes/sig0.9_iter20_viter50_nb_cv0.csv" 

Use grepl:

dataframes[!grepl("isce.log", dataframes, fixed=TRUE)]

[1] "saga/dataframes/no_filter.csv"
[2] "saga/dataframes/sig0.9_iter100_viter50_nb_cv0.csv"
[3] "saga/dataframes/sig0.9_iter20_viter50_nb_cv0.csv"

Data:

dataframes <- c("saga/dataframes/isce.log",
                "saga/dataframes/no_filter.csv",  
                "saga/dataframes/sig0.9_iter100_viter50_nb_cv0.csv",
                "saga/dataframes/sig0.9_iter20_viter50_nb_cv0.csv")

Or you can try:

grep("isce.log",dataframes,value=TRUE,invert=TRUE)

The option value=TRUE returns the value from your vector that matches, and you use invert=TRUE to flip..

Related