grep
can be used to actually return the matches instead of logical values:
lapply(species, grep, file.list, ignore.case=TRUE, value=TRUE)
#[[1]]
#[1] "blah_cod" "blah_cod"
#
#[[2]]
#[1] "blah_had"
Pregunta
I am trying to subset a vector based on a number of inputs. file.list will be a vector of filenames that I want to subset, and species will be the species names I want to search for within the files.
file.list <- c("blah_cod", "blah_had", "blah_ggu", "blah_cod")
species <- c("cod", "had")
a<-sapply(species, grepl, file.list, ignore.case=TRUE)
cod had
[1,] TRUE FALSE
[2,] FALSE TRUE
[3,] FALSE FALSE
[4,] TRUE FALSE
file.list[a[,1]]
file.list[a[,2]]
With the code I have currently I am able to get what I need, but I need to be able to automate it such that the number of columns will depend on the number of species input by the user. I tried looping like this:
for (i in (1:ncol(a))){b<-file.list[a[,i]]}
I have also tried a number of combinations along these lines, but either get only part of the information I need or errors. Any ideas?
Solución
grep
can be used to actually return the matches instead of logical values:
lapply(species, grep, file.list, ignore.case=TRUE, value=TRUE)
#[[1]]
#[1] "blah_cod" "blah_cod"
#
#[[2]]
#[1] "blah_had"