2014-03-03 3 views
1

각 행과 열의 수가 같은 .csv 파일 모음이 있습니다. 각 파일 A, B, C에 의해 특징 일부 피험자의 관찰 (열 '값')을 포함하고, 다음과 같은 형태로 취여러 개의 데이터 프레임 결합 및 집계

A B C value 
1 1 1 0.5 
1 1 2 0.6 
1 2 1 0.1 
1 2 2 0.2 
. . . . 

각 파일을 가정 별도의 데이터 프레임에 판독된다. '값'열에는 주어진 테스트 대상에 대한 모든 '값'행에 대한 일부 함수 호출의 결과를 의미하는 단일 데이터 프레임으로 이러한 데이터 프레임을 결합하는 가장 효율적인 방법은 무엇입니까? 열 A, B 및 C는 모든 파일에서 일정하며 이러한 관측을위한 키로 볼 수 있습니다.

도움 주셔서 감사합니다.

답변

2

이 파일이 모두 같은 방법으로 정렬 가정, 꽤 쉽게해야합니다 : 여기

dflist <- lapply(dir(pattern='csv'), read.csv) 
# row means: 
rowMeans(do.call('cbind', lapply(dflist, `[`, 'value'))) 
# other function `myfun` applied to each row: 
apply(do.call('cbind', lapply(dflist, `[`, 'value')), 1, myfun) 
0

는 키가 임의의 순서로, 또는 어쩌면 실종 수있는 경우에 또 다른 솔루션입니다 :

n <- 10 # of csv files to create 
obs <- 10 # of observations 
# create test files 
for (i in 1:n){ 
    df <- data.frame(A = sample(1:3, obs, TRUE) 
       , B = sample(1:3, obs, TRUE) 
       , C = sample(1:3, obs, TRUE) 
       , value = runif(obs) 
       ) 
    write.csv(df, file = tempfile(fileext = '.csv'), row.names = FALSE) 
} 


# read in the data 
input <- lapply(list.files(tempdir(), "*.csv", full.names = TRUE) 
    , function(file) read.csv(file) 
    ) 

# put dataframe together and the compute the mean for each unique combination 
# of A, B & C assuming that they could be in any order. 
input <- do.call(rbind, input) 
result <- lapply(split(input, list(input$A, input$B, input$C), drop = TRUE) 
    , function(sect){ 
     sect$value[1L] <- mean(sect$value) 
     sect[1L, ] 
    } 
) 

# create output DF 
result <- do.call(rbind, result) 
result