3

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...?

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Lenn
  • 1,283
  • 7
  • 20

3 Answers3

4

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" 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
3

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")
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

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..

StupidWolf
  • 45,075
  • 17
  • 40
  • 72
  • Great, thank you very much! Grep really seems the best tool for this. But why would I want to invert it? – Lenn Jun 27 '20 at 11:27
  • You want the values that don't have "isce.log" ? So it has to be the inverse. If you try ```grep("isce.log",dataframes,value=TRUE)``` you get values that have the pattern – StupidWolf Jun 27 '20 at 11:32
  • Of course.... Sorry, didn't have enough coffee yet – Lenn Jun 27 '20 at 11:46