OPのコメントに照らして更新
100万以上の行でこれを行うと、このように提供されるすべてのオプションが遅くなります。100,000行のダミーデータセットの比較タイミングは次のとおりです。
set.seed(12)
DF3 <- data.frame(id = sample(1000, 100000, replace = TRUE),
group = factor(rep(1:100, each = 1000)),
value = runif(100000))
DF3 <- within(DF3, idu <- factor(paste(id, group, sep = "_")))
> system.time(out1 <- do.call(rbind, lapply(split(DF3, DF3["group"]), `[`, 1, )))
user system elapsed
19.594 0.053 19.984
> system.time(out3 <- aggregate(DF3[,-2], DF3["group"], function (x) x[1]))
user system elapsed
12.419 0.141 12.788
私は百万行でそれらをやることをあきらめました。信じられないかもしれませんが、はるかに高速です。
out2 <- matrix(unlist(lapply(split(DF3[, -4], DF3["group"]), `[`, 1,)),
byrow = TRUE, nrow = (lev <- length(levels(DF3$group))))
colnames(out2) <- names(DF3)[-4]
rownames(out2) <- seq_len(lev)
out2 <- as.data.frame(out2)
out2$group <- factor(out2$group)
out2$idu <- factor(paste(out2$id, out2$group, sep = "_"),
levels = levels(DF3$idu))
出力は(事実上)同じです:
> all.equal(out1, out2)
[1] TRUE
> all.equal(out1, out3[, c(2,1,3,4)])
[1] "Attributes: < Component 2: Modes: character, numeric >"
[2] "Attributes: < Component 2: target is character, current is numeric >"
out1
( (またはout2
)とout3
(バージョン)の違いaggregate()
は、コンポーネントの行名だけです。)
タイミング:
user system elapsed
0.163 0.001 0.168
100,000行の問題、およびこの100万行の問題について:
set.seed(12)
DF3 <- data.frame(id = sample(1000, 1000000, replace = TRUE),
group = factor(rep(1:1000, each = 1000)),
value = runif(1000000))
DF3 <- within(DF3, idu <- factor(paste(id, group, sep = "_")))
のタイミングで
user system elapsed
11.916 0.000 11.925
マトリックスバージョン(を生成するout2
)での作業は、他のバージョンが100,000行の問題を実行する場合よりも100万行を実行する方が高速です。これは、マトリックスの操作が実際に非常に高速であることを示しています。私のdo.call()
バージョンのボトルネックはrbind()
、結果をまとめることです。
百万行の問題のタイミングは次のように行われました。
system.time({out4 <- matrix(unlist(lapply(split(DF3[, -4], DF3["group"]),
`[`, 1,)),
byrow = TRUE,
nrow = (lev <- length(levels(DF3$group))))
colnames(out4) <- names(DF3)[-4]
rownames(out4) <- seq_len(lev)
out4 <- as.data.frame(out4)
out4$group <- factor(out4$group)
out4$idu <- factor(paste(out4$id, out4$group, sep = "_"),
levels = levels(DF3$idu))})
オリジナル
たとえば、データが次のようになっている場合はDF
、次のようになります。
do.call(rbind, lapply(with(DF, split(DF, group)), head, 1))
あなたが望むことをします:
> do.call(rbind, lapply(with(DF, split(DF, group)), head, 1))
idu group
1 1 1
2 4 2
3 7 3
新しいデータが入っている場合は、次のDF2
ようになります。
> do.call(rbind, lapply(with(DF2, split(DF2, group)), head, 1))
id group idu value
1 1 1 1_1 34
2 4 2 4_2 6
3 1 3 1_3 34
ただし、速度を上げるために、使用する代わりにサブセット化することをお勧めします。head()
使用しないことで少し利益を得ることができますwith()
。例:
do.call(rbind, lapply(split(DF2, DF2$group), `[`, 1, ))
> system.time(replicate(1000, do.call(rbind, lapply(split(DF2, DF2$group), `[`, 1, ))))
user system elapsed
3.847 0.040 4.044
> system.time(replicate(1000, do.call(rbind, lapply(split(DF2, DF2$group), head, 1))))
user system elapsed
4.058 0.038 4.111
> system.time(replicate(1000, aggregate(DF2[,-2], DF2["group"], function (x) x[1])))
user system elapsed
3.902 0.042 4.106