は、例えば、データ、コードと問題の説明です:この条件付き結合を高速化するには(forループが遅い)?ここ
require(data.table)
require(dplyr)
df1 <- read.table(text= "
col1 col2 col3 col4 col5
123 121 16519 1 4
123 121 16519 2 5
123 121 16518 3 5
123 121 16517 4 6
123 121 16512 5 7
123 121 16554 6 8
124 333 16554 7 9
124 333 16552 8 5
124 333 16549 1 1
124 333 16495 2 2
124 555 16573 4 4
125 555 16573 5 3
125 555 16569 6 5
125 555 16567 7 6
125 555 16568 8 7
", header=TRUE, na.strings=NA, stringsAsFactors=FALSE)
df2 <- distinct(df1[c("col1","col2","col3")])
setnames(df2, old=c("col1","col2","col3"), new=c("col11","col22","col33"))
res <- vector("list", nrow(df2))
for(i in 1:nrow(df2)) {
one_row <- df2[i,]
df <- merge(select(one_row, col11, col22, col33),
select(df1,col1,col2,col3,col4,col5),by=NULL)%>%
filter((col3 >= (col33-(7))) & (col3 < col33))
res[[i]] = df%>%
group_by(col11, col22,col33)%>%
summarise(Averagecol4=mean(col4,na.rm=TRUE), Count=n())
}
as.data.frame(do.call("rbind", res))
# col11 col22 col33 Averagecol4 Count
# 1 123 121 16519 4.0 3
# 2 123 121 16518 4.5 2
# 3 123 121 16517 5.0 1
# 4 123 121 16554 4.5 2
# 5 124 333 16554 4.5 2
# 6 124 333 16552 1.0 1
# 7 124 555 16573 7.0 3
# 8 125 555 16573 7.0 3
# 9 125 555 16569 7.5 2
# 10 125 555 16568 7.0 1
- コードが
data.frame
を作成します。 - は、次に次にDF2の列名の名前を変更する3つの列
- の唯一明確な(またはユニーク)の組み合わせを考慮して、そこから別の
data.frame
を作成します。 res
を作成し、df2
の各行に対して、df1
で結合を実行し、条件付きフィルタリングを実行し、対応するインデックスres
に結果を格納します。rbind
最終結果はdata.frame
です。
問題は、nrow(df1) = ~225,000
の場合、多くの時間がかかります。どうすればスピードアップできますか?
あなたのコードはすぐにエラーになります。 'setnames'はどこからですか?それは 'setNames'の別のバージョンですか? – alistaire
@alistaire指摘してくれてありがとう。その固定! – KGarg
まだ 'res'がdata.frameとして終わっていないので、エラーが出ています。より良い質問:あなたの希望する出力は何ですか? – alistaire