2014-10-30 99 views
2

如果我只有部分名称包括开始或结束字符,如何从R中的文件中读取数据?从R中的文件中读取名称中的部分名称

感谢

+2

如何使用'list.files()'来获取所有列表文件在工作目录中,然后看哪一个符合你的标准,然后阅读它。你已经提供了很少的细节,很难更具体。 – MrFlick 2014-10-30 06:17:37

回答

5

您可以使用list.files,其中有一个pattern的说法,要尽量接近你可以匹配。

writeLines(c('hello', 'world'), '~/tmp/example_file_abc') 
filename <- list.files(path = '~/tmp', pattern = 'file_abc$', full.names = TRUE)[1] 
readLines(filename) 
# [1] "hello" "world" 
0

还有Sys.glob这将扩大使用根据glob语法明星和问号的格式。

这里它包裹在一个函数中,以匹配表格"first*last"的文件名,其中"*"是任何东西。如果你真的在你的名星或其他特殊字符...那么你需要做的更多一点。不管怎么样:

> match_first_last = function(first="", last="", dir=".") 
    {Sys.glob(
     file.path(dir,paste(first,"*",last,sep="")) 
    ) 
    } 


# matches "*" and so everything: 
> match_first_last() 
[1] "./bar.X" "./foo.c" "./foo.R" 

# match things starting `foo`  
> match_first_last("foo") 
[1] "./foo.c" "./foo.R" 

# match things ending `o.c` 
> match_first_last(last="o.c") 
[1] "./foo.c" 

# match start with f, end in R 
> match_first_last("f","R") 
[1] "./foo.R"