16

data.table を使用して、3 つの変数のグループで一番上の行を取得しようとしています。

私は実用的な解決策を持っています:

col1 <- c(1,1,1,1,2,2,2,2,3,3,3,3)
col2 <- c(2000,2000,2001,2001,2000,2000,2001,2001,2000,2000,2001,2001)
col4 <- c(1,2,3,4,5,6,7,8,9,10,11,12)
data <- data.frame(store=col1,year=col2,month=12,sales=col4)

solution1 <- data.table(data)[,.SD[1,],by="store,year,month"]

次のリンクで Matthew Dowle によって提案されたより遅いアプローチを使用しました。

https://stats.stackexchange.com/questions/7884/fast-ways-in-r-to-get-the-first-row-of-a-data-frame-grouped-by-an-identifier

より高速な自己結合を実装しようとしていますが、機能させることができません。

誰か提案はありますか?

4

2 に答える 2

3

どうですか:

solution2 <- data.table(data)[ , sales[1], by="store,year,month"]
> solution2
   store year month V1
1:     1 2000    12  1
2:     1 2001    12  3
3:     2 2000    12  5
4:     2 2001    12  7
5:     3 2000    12  9
6:     3 2001    12 11

その列の名前を変更できると思います:

data.table(data)[,fsales := sales[1],by="store,year,month"]
于 2013-04-02T23:22:57.047 に答える