2017-05-15 10 views
1

가져 오기 다중 데이터 (excel 또는 csv)에 대한 질문이 있습니다. 나는 한 번에 여러 엑셀 데이터 (같은 열 이름)를 읽으려면 내가 아는
는 코드는 다음과 같습니다형식으로 데이터 가져 오기

library(readxl) 
file.list <- dir(path = "/path", pattern='\\.xlsx', full.names = T) 
df.list <- lapply(file.list, read_excel) 
data <- rbindlist(df.list) 

그래서, 내가 동시에 그들을 읽고 하나 개의 데이터로 결합한다.
그러나 나는 나의 데이터 중 하나를 예로 들었다. Excel에서
, ROW1 타이틀 이름과이 header입니다 ROW2을 가지고, 그래서 obs.row3에서 시작됩니다. 첫번째 데이터 EXCEL이 보이는 경우
또한 :

TITLE~~~~~ 
col1 col2 col3 
A  1  3.59283E+14 
B  2  3.59258E+14 
C  3  3.59286E+14 
REFUND 
A  -1  3.59286E+14 

그러나 col3은 Excel에서 숫자로 정의된다.

TITLE~~~~~ 
col1 col2 col3 
A  1  359283060959987 
B  2  359258069826064 
C  3  359286062903911 
REFUND 
A  -1  359283060959987 

Row6REFUND 있습니다처럼 실제로, 그것은 보인다. 내 여러 데이터에서 어떤 행에 REFUND이 있는지 알지 못합니다. 나는 나의 obs를 읽고 싶다. 이 행이 없습니다. 어떻게해야합니까?
사실 col3character입니다. 그러나 엑셀에서는 numeric처럼 보입니다.
R로 가져올 때 character으로 정의 할 수 있습니다. 따라서 가져온 후에는 지수 기호가 표시되지 않습니다.

답변

2

적어도 read_excel 기능을 사용하여 REFUND 행이 없으면 데이터를 직접 읽을 수있는 방법이 없다고 생각합니다. 그러나 나는 R이 아주 새롭고 잘못 될 수 있습니다.

즉, 나에게 발생하는 첫 번째 일은 자신의 기능을 만드는 것입니다. 아래 하나가 작동하는 것 같습니다.

library(readxl) 
library(data.table) 

file.list <- dir(path = ".", pattern='\\.xlsx', full.names = T) 

my_read_data<-function(x){ #x list of files 

    df.list<- lapply(x, function(x){read_excel(path=x,skip=1,col_names = TRUE, 
              col_types=c("text","numeric","text"))}) 
    #skip -> skip the line with the title 
    #col_names -> use the first row as column names, i.e., col1, col2 and col3 
    #col_types-> vector containing one entry per column indicating the type of data 

    my.data <- rbindlist(df.list) 
    my.data.clean<-my.data[my.data$col1!="REFUND",] #select only rows without "REFUND" 

    return(my.data.clean) 
} 

기능을 실행하려면 REFUND 행의 위치를 ​​변경하여 Excel 예제를 네 번 복사하십시오. 내가 얻은 결과는 다음과 같이 입니다.

the.data<-my_read_data(file.list) 

>the.data 
    col1 col2   col3 
1: A 1 359283060959987 
2: B 2 359258069826064 
3: C 3 359286062903911 
4: A -1 359283060959987 
5: A 1 359283060959987 
6: B 2 359258069826064 
7: C 3 359286062903911 
8: A -1 359283060959987 
9: A 1 359283060959987 
10: B 2 359258069826064 
11: C 3 359286062903911 
12: A -1 359283060959987 
13: A 1 359283060959987 
14: B 2 359258069826064 
15: C 3 359286062903911 
16: A -1 359283060959987 

편집 - 열을 전달하는 기능이 어쩌면 당신 대신이 기능을 고려할 수 있습니다 싶어, 당신의 의견에 대해서는 문자 유형

로 변경하기 :

my_read_data2<-function(x,character_col=NULL){ #x->list of files 
               # character_col->column to be change to character 
               # can be more than one 

    df.list<- lapply(x, function(x){read_excel(path=x,skip=1,col_names = TRUE)}) 
    my.data <- rbindlist(df.list) 
    my.data.clean<-my.data[my.data$col1!="REFUND",] #select only rows without "REFUND" 

    # changing column selected by character_col to character 
    # since the result from step above is a data table, 
    # access to elements is different from data frame 

    if(!is.null(character_col)){ #this allow you to use the function using only 
           # default results from read_excel 

     my.data.clean[, eval(character_col):= lapply(.SD, as.character), 
        .SDcols= character_col] 
    } 
    # eval -> you need to evaluate the argument you pass to the function, 
    #   otherwise you'll end up with an additional character_col column 
    #   that will be a list of all the columns you include in .SDcols 
    #.SD -> is the subset of the data table, in this case 
    #  .SDcols specifies the columns that are included in .SD. 

    return(my.data.clean[]) # in that case, don't forget the [] to avoid 
          #the odd behaviour when calling your resulting data table 
          #(see link at the end)        
} 

예를 :

the.data<-my_read_data2(file.list) 
str(the.data) 

>str(the.data) 
    Classes ‘data.table’ and 'data.frame': 16 obs. of 3 variables: 
    $ col1: chr "A" "B" "C" "A" ... 
    $ col2: num 1 2 3 -1 1 2 3 -1 1 2 ... 
    $ col3: num 3.59e+14 3.59e+14 3.59e+14 3.59e+14 3.59e+14 ... 
    - attr(*, ".internal.selfref")=<externalptr> 

the.data1<-my_read_data2(file.list,"col3") 
str(the.data1) 

> str(the.data1) 
    Classes ‘data.table’ and 'data.frame': 16 obs. of 3 variables: 
    $ col1: chr "A" "B" "C" "A" ... 
    $ col2: num 1 2 3 -1 1 2 3 -1 1 2 ... 
    $ col3: chr "359283060959987" "359258069826064" "359286062903911" "359283060959987" ... 
    - attr(*, ".internal.selfref")=<externalptr> 

하나 이상의 열 :

the.data2<-my_read_data2(file.list,c("col2","col3")) 
the.data3<-my_read_data2(file.list,c(2,3))  

data.table objects not printed after returned from function

는 희망이 굉장 당신

+1

에게 도움이됩니다. 'col_types'에 관한 또 다른 작은 질문입니다. 열 이름을 지정할 수 있습니까?like :'col_types = c ("col3"= "text")' –

+2

안녕하세요 @ Peter Chen은 이미 말했듯이 전문가는 아니지만 col_types는 위치 기반에서만 작동한다고합니다. 형식이 벡터에 의해 제공된 순서에 따라 정렬된다는 것을 의미합니다. 사실, 6 개의 열과 3 개의 유형 만 정의 되었다면,이 3 가지 유형은 마지막 3 개의 열에 대해 재활용 될 것입니다. read_excel에서 유형을 추측하고 나중에 변수 유형을 변환하도록 데이터를 가져올 수 있습니다. –