0

私のデータフレーム「lotsadates」からのデータは次のようになります。

>Date

1 2012-09-26
2 2012-09-26
3 2012-09-26
4 2012-09-27
5 2012-09-28
6 2012-09-28

同じ長さのday_of_weekベクトルがあります。

> day_of_week

1 3
2 3
3 3
4 4
5 5
6 5

日付ごとの観測数をカウントするために、以下を使用しています。

ndist <-tapply(1:NROW(lotsadates), 
               lotsadates$Date, 
               function(x) length(unique(x)))

したがって、ndistは次のようになります。

Obs / Date / ndist
1 / 2012-09-26 / 3
2 / 2012-09-27 / 1
3 / 2012-09-28 / 2

しかし、私はndistを次のように見せたいです:

日付/ndist/ day_of_week
1 / 2012-09-26 / 3/3
2 / 2012-09-27 / 1/4 3 / 2012-09-28
/ 2/5

かなり簡単な解決策があると思いますが、理解できません。あなたの提案は大歓迎です!

4

3 に答える 3

3

data.tableエレガンスをコーディングするためのアプローチ

library(data.table)
# assuming lotsadates has 2 columns, Date and day_of_wee
DT <- as.data.table(lotsadates)
DT[, .N, by = list(Date, day_of_week)]
于 2012-10-16T05:20:16.090 に答える
2
library(reshape2)
result <- dcast(lotsadates, Date ~., value.var='day_of_week')
result$day_of_week <- as.POSIXlt(result$Date)$wday
names(result)[2] <- "ndist"
> result
        Date ndist day_of_week
1 2012-09-26     3           3
2 2012-09-27     1           4
3 2012-09-28     2           5
于 2012-10-10T22:50:30.840 に答える
1
library(plyr)
# assuming lotsadates has 2 columns, Date and day_of_week
ndist <- ddply(lotsadates, .(Date, day_of_week), summarise, n=length(Date))
于 2012-10-11T00:53:56.977 に答える