当我有文件名的一部分时,从R中的文件读取

当我有文件名的一部分时,从R中的文件读取,r,R,当我只有文件名的一部分(包括起始字符或结束字符)时,如何读取R中的文件 谢谢您可以使用list.files,它有一个模式参数,尝试尽可能接近匹配 writeLines(c('hello', 'world'), '~/tmp/example_file_abc') filename <- list.files(path = '~/tmp', pattern = 'file_abc$', full.names = TRUE)[1] readLines(filename) # [1] "hello

当我只有文件名的一部分(包括起始字符或结束字符)时,如何读取R中的文件


谢谢

您可以使用
list.files
,它有一个
模式
参数,尝试尽可能接近匹配

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"
writeLines(c('hello','world'),“~/tmp/example\u file\u abc')

filename还有
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"

如何使用
list.files()
获取工作目录中所有文件的列表,然后查看哪个文件符合您的条件,然后读取它。你提供的细节太少,很难更具体。