2016-04-05 7 views
0

大きなデータフレーム(> 1.000.000エントリ)があります.1つの列には日付/時刻変数が含まれ、1つの列には数値が含まれています。問題は、日付/時刻変数の一部が2回または3回発生し、それぞれの数値を平均する必要があるため、日付/時刻変数ごとに1つの数値が得られることです。大きなデータを集計するフレーム

今まで、私は次のことをやっている:

## audio_together is the dataframe with two colums $timestamp and $amplitude 
## (i.e. the numeric value) 

timestamp_unique <- unique(audio_together$timestamp) ## find all timestamps 
    audio_together3 <- c(rep(NA, length(timestamp_unique))) ## audio_together 3 is the new vector containing the values for each timestamp 
    count = 0 
    for (k in 1:length(timestamp_unique)){ 
    temp_time <- timestamp_unique[k] 
    if (k==1){ 
     temp_subset <- audio_together[(1:10),] ## look for timestamps only in a subset, which definitely contains the timestamp we are looking for 
     temp_data_which <- which(temp_subset$timestamp == temp_time) 
    } else { 
     temp_subset <- audio_together[((count):(count+9)),] 
     temp_data_which <- which(temp_subset$timestamp == temp_time) 
    } 
    if (length(temp_data_which) > 1){ 
     audio_together3[k] <- mean(temp_subset$amplitude[temp_data_which], na.rm = T) 
    } else { 
     audio_together3[k] <- temp_subset$amplitude[temp_data_which] 
    } 
    count <- count + length(temp_data_which) 
    } 

しかし、このプロセスはまだかなり遅いです。重要なアイデア(つまり、分単位で)はプロセスをスピードアップしますか?

UPDATE:例

timestamp <- c("2015-09-03 18:54:13", "2015-09-03 18:54:14", "2015-09-03 18:54:14", "2015-09-03 18:54:15", "2015-09-03 18:54:15", "2015-09-03 18:54:16", "2015-09-03 18:54:16", "2015-09-03 18:54:17", "2015-09-03 18:54:17") 
amplitude <- c(200, 313, 321, 432, 111, 423, 431, 112, 421) 

audio_together <- data.frame(timestamp, amplitude) 
+0

あなたはあなたのデータの小さな大きなサンプルと予想される出力を提供することはできますか?あなたが望むようなグループ化は、ベースRの 'tapply'、' ave'、 'aggregate'といったいろいろな方法で処理されます。' data.table'と 'dplyr'パッケージは、必要な速度を提供する可能性が非常に高いでしょう。 – nicola

+1

'ライブラリ(data.table); setDT(audio_together); audio_together [、。(振幅=平均(振幅、na.rm =真))、by =タイムスタンプ] ' – Roland

+1

[this](http://stackoverflow.com/questions/21982987/mean-per-group-データフレーム内)? –

答えて

0

それはminimal reproducible exampleのせずにテストすることは困難ですが、あなたの意図は、すべてのamplitudeが同じtimestampを共有して平均化することであるならば、このdplyrソリューションが役立つことがあります。

library(dplyr) 
audio_together %>% 
    group_by(timestamp) %>% 
    summarize(av_amplitude=mean(amplitude, na.rm=T)) %>% 
    ungroup() 
0

感謝あなたのアイデアのために。

次の作品は完璧:

require(dplyr) 
audio_together <- audio_together %>% group_by(timestamp) 
audio_together <- ungroup(audio_together %>% summarise(mean(amplitude, na.rm=T)))