开发者

trying to prune down a list of files

开发者 https://www.devze.com 2022-12-30 08:21 出处:网络
I have a list of files and I\'m trying to extract all layer1_*.grd files. Is there a way of doing this in one grep expression?

I have a list of files and I'm trying to extract all layer1_*.grd files. Is there a way of doing this in one grep expression?

lof <- c("layer1_1.grd", "layer1_1.gri", "layer1_2.grd", "layer1_2.gri", 
"layer1_3.grd", "layer1_3.gri", "layer1_4.grd", "layer1_4.gri", 
"layer1_5.grd", "layer1_5.gri", "layer2_1.grd", "layer2_1.gri", 
"layer2_2.grd", "layer2_2.gri", "layer2_3.grd", "layer2_3.gri", 
"layer2_4.grd", "layer2_4.gri", "layer2_5.grd", "layer2_5.gri", 
"layer3_1.grd", "layer3_1.gri", "layer3_2.grd", "layer3_2.gri", 
"layer3_3.grd", "layer3_3.gri", "layer3_4.grd", "layer3_4.gri", 
"layer3_5.grd", "layer3_5.gri", "layer4_1.grd", "layer4_1.gri", 
"layer4_2.grd", "layer4_2.gri", "layer4_3.grd", "layer4_3.gri", 
"layer4_4.grd", "layer4_4.gri", "layer4_5.grd", "layer4_5.gri")

I tried doing this in two steps:

list.of.files <- list.files(pattern = c("1_"))
list.of.files <- list.of.files[grep(".grd", list.of.files)]

Can someone enlighten me how to do 开发者_如何学Gothis with grep in one step? I naively tried passing list() and c() to the grep but, as you can imagine, it doesn't work.

list.of.files <- list.files()
list.of.files <- list.of.files[grep(list("1_", ".grd"), list.of.files)]


This should work for you:

> lof[grep("layer1_.*.grd", lof)]
[1] "layer1_1.grd" "layer1_2.grd" "layer1_3.grd" "layer1_4.grd" "layer1_5.grd"

Also, just to clarify your terminology: your list of files is not really a list; it's a character vector.


The stringr alternative is lof[str_detect(lof, "layer1_.*.grd")].

In fact, in this case you can be even more specific about the missing characters, so "layer1_[[:digit:]].grd" would work as the pattern here, and might be faster if lof is very long.

0

精彩评论

暂无评论...
验证码 换一张
取 消