2014-10-30 2 views
2

시작 문자 또는 끝 문자를 포함하여 이름의 일부만 가지고있을 때 R의 파일에서 어떻게 읽을 수 있습니까?이름의 일부일 때 R에서 파일 읽기

감사

+2

'list.files 사용에 대한()'모든 목록을 얻는 방법 파일을 작업 디렉토리에 저장 한 다음, 어떤 파일이 기준과 일치하는지 확인한 다음 읽습니다. 좀 더 자세히 설명하기는 어렵습니다. – MrFlick

답변

5

당신이하는 pattern 인수를 가지고 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" 
0

glob 구문에 따라 별과 물음표를 사용하여 패턴을 확대 할 Sys.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" 
관련 문제