2017-11-24 1 views
0

저는 R에 익숙하지 않으며 루프를 수행하는 방법을 정확히 모릅니다. 내 문제는 다음과 같습니다. 폴더에 각각 약 160 개의 csv 파일이 있으며 각 파일에는 특정 이름이 있습니다. 각 파일에는 "HL.X.Y.Z."패턴이 있습니다. 여기서 X = "Region", Y = "cluster"및 Z = "point"입니다. 내가해야 할 일은이 모든 csv 파일을 읽고, 이름에서 문자열을 추출하고, 각 csv 파일에 대한 문자열로 열을 만들고, 모든 csv 파일을 단일 데이터 프레임에 바인딩하는 것입니다. 여기 는 내가 뭘하려고 오전 일부 코드 : r에있는 여러 csv 파일의 cbind 열

setwd("C:/Users/worddirect") 
files.names<-list.files(getwd(),pattern="*.csv") 
files.names 
head(files.names) 
>[1] "HL.1.1.1.2F31CA.150722.csv" "HL.1.1.2.2F316A.150722.csv" 
[3] "HL.1.1.3.2F3274.150722.csv" "HL.1.1.4.2F3438.csv"   
[5] "HL.1.10.1.3062CD.150722.csv" "HL.1.10.2.2F343D.150722.csv" 

모든 파일을 읽을 같이 이렇게 잘 작동합니다 :

files.names 
    for (i in 1:length(files.names)) { 
    assign(files.names[i], read.csv(files.names[i],skip=18)) 
      } 

을이 작품 같은 개별 CSV 파일을 추가로 열 추가 괜찮음 :

test<-cbind("Region"=rep(substring(files.names[1],4,4),times=nrow(HL.1.1.1.2F31CA.150722.csv)), 
     "Cluster"=rep(substring(files.names[1],6,6),times=nrow(HL.1.1.1.2F31CA.150722.csv)), 
     "Point"=rep(substring(files.names[1],8,8),times=nrow(HL.1.1.1.2F31CA.150722.csv)), 
     HL.1.1.1.2F31CA.150722.csv) 
head(test) 
    Region Cluster Point   Date.Time Unit Value 
1  1  1  1 6/2/14 11:00:01 PM C 24.111 
2  1  1  1 6/3/14 1:30:01 AM C 21.610 
3  1  1  1 6/3/14 4:00:01 AM C 20.609 

그러나 위의 루프는 작동하지 않습니다.

files.names 
    for (i in 1:length(files.names)) { 
    assign(files.names[i], read.csv(files.names[i],skip=18)) 
    cbind("Region"=rep(substring(files.names[i],4,4),times=nrow(i)), 
     "Cluster"=rep(substring(files.names[i],6,6),times=nrow(i)), 
     "Point"=rep(substring(files.names[i],8,8),times=nrow(i)), 
     i) 
      } 
>Error in rep(substring(files.names[i], 4, 4), times = nrow(i)) : 
    invalid 'times' argument 

최종 단계는 모든 데이터 파일을 단일 데이터 프레임에 바인딩하는 것입니다.

나는 어떤 제안을 주셔서 감사합니다. 내가 한 일을하는 더 간단한 방법이 있다면 나는 또한 감사한다!

답변

0

R.이 문제가 apply() 기능을 함께 해결하기보다 R-같은 방법으로 문제를 해결하는 방법에는 여러 가지가 있습니다. apply() 패밀리는 암시 된 for 루프와 같은 역할을하며 함수 인수를 통해 전달 된 각 항목에 하나 이상의 연산을 적용합니다.

R의 또 다른 중요한 특징은 익명의 기능입니다. 익명 함수와 lapply()을 결합하면 다중 파일 읽기 문제를 해결할 수 있습니다.

setwd("C:/Users/worddirect") 
files.names<-list.files(getwd(),pattern="*.csv") 
# read csv files and return them as items in a list() 
theList <- lapply(files.names,function(x){ 
    theData <- read.csv(x,skip=18) 
    # bind the region, cluster, and point data and return 
    cbind(
      "Region"=rep(substring(x,4,4),times=nrow(theData)), 
      "Cluster"=rep(substring(x,6,6),times=nrow(theData)), 
      "Point"=rep(substring(x,8,8),times=nrow(theData)), 
      theData) 
}) 
# rbind the data frames in theList into a single data frame 
theResult <- do.call(rbind,theList) 

안부,

+0

야, 너 마술사 야! 완벽하게 일했습니다. 따라서이 경우 "read.csv (x)"가 작동하는 이유는 무엇입니까? 나는 각 csv를 읽고 다른 컬럼을 추가하기 위해'for' 루프를 수행해야한다고 생각했다. –

+0

Hello @CaesarGan. 필자는이 기술의 세부 사항을 [Extract Operator - Assignment 1 Concepts] 형식 (https : // github.존스 홉킨스 데이터 과학 전문화 * R 프로그래밍을 지원하기 위해 썼던 com/lgreski/datasciencectacontent/blob/master/markdown/rprog-extractOperator.md # concepts-for-r-programming ---- 프로그래밍 - 할당 -1) * 코스. 또한 도움이된다면 답을 수락하거나/upvote하십시오. –

+0

굉장합니다, 고마워요! –

0

i은 nrow 속성이없는 번호입니다.

당신은 코드를 사용할 수 있습니다

result = data.frame() 

for (i in 1:length(files.names)) { 
    assign(files.names[i], read.csv(files.names[i],skip=18)) 
    result = rbind(
        cbind(
         "Region"=rep(substring(files.names[i],4,4),times=nrow(files.names[i])), 
         "Cluster"=rep(substring(files.names[i],6,6),times=nrow(files.names[i])), 
         "Point"=rep(substring(files.names[i],8,8),times=nrow(files.names[i])), 
         files.names[i])) 
} 
+0

Kppatel 파텔, 흥미, 감사합니다. 불행하게도이 경우 여전히 동일한 오류가 발생합니다. "부분 오류 (부분 문자열 (files.names [4], times = nrow (i))) : 'times'인수가 잘못되었습니다." 여전히이 루프를 사용하여 각 CSV 파일의 행 수를 얻는 방법을 모르겠다. (각각의 CSV는 다른 nrows를 가짐) –

+0

Rstudio 또는 R을 사용하고 있습니까? Rstudio를 사용하고 있다면 break inside loop를 사용하여 무엇을 볼 수 있습니까? 중단 점 중에 발생합니다. 또는 단지 기본 print 문을 사용할 수 있습니다. –

+0

흠, 그 사실을 알지 못했습니다. 굉장해. 나는 팁을 바르게 평가한다! –