2013-06-06 3 views
1

쉼표로 구분 된 파일이든 탭으로 구분 된 파일이든 상관없이 파일 형식을 읽고 csv 파일을 읽어야합니다. 다음 코드를 사용하고 있지만 입력 파일이 쉼표로 구분 된 파일 인 경우 파일을 두 번 읽어야하므로 비효율적입니다. 다음과 같이 내가 사용하는 코드는 다음과 같습니다R : 전체 내용을 읽지 않고 csv 파일의 유형을 예측하십시오.

readFile <- function(fileName){ 
    portData <- read.csv(fileName,sep="\t") 
    if(length(portData) == 1){ 
    print("comma separated file") 
    executeCommaSepFile(fileName) 
    } 
    else{ 
    print("tab separated file") 
    #code to process the tab separated file 
    } 
} 
executeCommaSepFile <- function(fileName){ 
    csvData <- read.csv(file=fileName, colClasses=c(NA, NA,"NULL",NA,"NULL",NA,"NULL","NULL","NULL")) 
    #code to process the comma separated file 
} 

는 파일의 전체 내용을 읽지 않고 파일의 유형을 예측 할 수 있습니까? 내가 portData 대신 fileName으로 전달하는 경우 나, 나는이 형식 executeCommaSepFile() 내부의 데이터를 얻을 :

RUS1000.01.29.1999.21st.Centy.Ins.Group.TW.Z.90130N10.72096.1527.534.0.01.21.188 
1   RUS1000,01/29/1999,3com Corp,COMS,88553510,358764,16861.908,0.16,47.000 
2    RUS1000,01/29/1999,3m Co,MMM,88579Y10,401346,31154.482,0.29,77.625 
3 RUS1000,01/29/1999,A D C Telecommunicat,ADCT,00088630,135114,5379.226,0.05,39.813 
4   RUS1000,01/29/1999,Abbott Labs,ABT,00282410,1517621,70474.523,0.66,46.438 

이이 read.csv(file=fileName, colClasses=c(NA, NA,"NULL",NA,"NULL",NA,"NULL","NULL","NULL")의 형식으로 변환 할 수 있나요)? 이 형식 즉 :

RUS1000 X01.29.1999 TW.Z X72096 
1 RUS1000 01/29/1999 COMS 358764 
2 RUS1000 01/29/1999 MMM 401346 
3 RUS1000 01/29/1999 ADCT 135114 
4 RUS1000 01/29/1999 ABT 1517621 
+1

임의 배열의 요소는 공동 수 있기 때문에, 분리가 무엇인지 알 수있는 방법이 없습니다 임의의 문자를 찾습니다. csv와 tsv 파일이 잘 작동한다고 믿는다면'readLines'를 사용하여 몇 줄을 만들고'grep'을 사용하여 쉼표 나 탭이 있는지 확인하십시오. –

답변

2
portData <- read.csv(fileName,sep="\t") 
if(length(portData) == 1) { 
    print("comma separated file") 
    dat <- read.csv(textConnection(portData)) 
    executeCommaSepFile(dat) # pass the data frame, not the filename 
} 
else { 
    print("tab separated file") 
    #code to process the tab separated file 
} 
1

기본 R와 함께 머물 경우, 당신은 적어도 두 가지 옵션이 있습니다.

파일 (nrows 인수 read.table 및 친구)의 작은 부분에서 읽기 : 전체 파일에

portData <- read.csv(fileName,sep="\t", nrows=1) 
if(length(portData) == 1) { 
    print("comma separated file") 
    executeCommaSepFile(fileName) 
} 
else { 
    print("tab separated file") 
    executeTabSepFile(fileName) # run read.table in here 
} 

읽기 및 작동하지 않은 경우로 돌아 가지 않기 위해 textConnection를 사용 디스크 (효율적이지,하지만 작동) : 일반적인 경우

portData <- read.csv(fileName,sep="\t") 
if(length(portData) == 1) { 
    print("comma separated file") 
    dat <- read.csv(textConnection(portData)) 
    executeCommaSepFile(dat) # pass the data frame, not the filename 
} 
else { 
    print("tab separated file") 
    #code to process the tab separated file 
} 
+0

이 작품은 ZZ !!! 고맙습니다 :) –

관련 문제