0

I am trying to delete all values in a list that have the tag ".dsw". My list is a list of files using the function list.files. This is my code:

for (file in GRef) {
  if (strsplit(file, "[.]")[[1]][3] == "dsw") {
     #GRef=GRef[-file]
    for(n in 1:length(GRef)){
      if (GRef[n] == file){
        GRef=GRef[-n]
      }
    }
  }
}

Where GRef is the list of file names. I get the error listed above, but I dont understand why. I have looked at this post: Error .. missing value where TRUE/FALSE needed, but I dont think it is the same thing.

Community
  • 1
  • 1
naveace
  • 65
  • 1
  • 8
  • 1
    Please provide more detail: show a sample of the content in `GRef`. – Abdou Jul 27 '16 at 15:25
  • you probaby have an NA in the first outer `if` statement. Put a `print` call right before the `if` printing the left hand side of the equality. – Adam Jul 27 '16 at 15:26
  • It is likely the result of a file that only has a single `.` in it, which means indexing it at 3 would be out of bounds – Adam Jul 27 '16 at 15:28

1 Answers1

0

You shouldn't attempt to to modify a vector while you are looping over it. The problem is your are removing items you are then trying to extract later which is causing the missing values. It's better to identify all the items you want remove first, then remove them. For example

GRef <- c("a.file.dsw", "b.file.txt", "c.file.gif", "d.file.dsw")
exts <- sapply(strsplit(GRef, "[.]"), `[`, 3)
GRef <- GRef[exts!="dsw"]
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • That works for the most part. would you be able to explain the syntax used? (i.e. why use sapply(strsplit(GRef,"[.]"),`[`,3) EDIT: My main misunderstand is with the `[`. what does that do? – naveace Jul 27 '16 at 15:42
  • `strsplit` returns a list. The `sapply` iterates over that list and the `[` is the subsetting function so it extracts the third element from each vector in the list. – MrFlick Jul 27 '16 at 17:58