3

我正在处理一个大型数据集,下面可以显示一个示例。对于我必须处理的大多数单个文件,应该有超过一天的数据。

Date <- c("05/12/2012 05:00:00", "05/12/2012 06:00:00", "05/12/2012 07:00:00",
          "05/12/2012 08:00:00", "06/12/2012 07:00:00", "06/12/2012 08:00:00", 
          "07/12/2012 05:00:00", "07/12/2012 06:00:00", "07/12/2012 07:00:00",
          "07/12/2012 08:00:00")
Date <- strptime(Date, "%d/%m/%Y %H:%M")
c <- c("0","1","5","4","6","8","0","3","10","6")
c <- as.numeric(c)
df1 <- data.frame(Date,c,stringsAsFactors = FALSE)

我希望只留下一天的数据。这一天将通过当天的数据点最多来选择。如果由于任何原因两天被捆绑(具有最大数据点数),我希望选择记录的个人价值最高的一天。

在上面给出的示例数据框中,我将留下 12 月 7 日。它有 4 个数据点(与 12 月 5 日一样),但它具有这两天中记录的最高值(即 10)。

4

3 回答 3

4

一个data.table解决方案:

dt <- data.table(df1)
# get just the date
dt[, day := as.Date(Date)]
setkey(dt, "day")
# get total entries (N) and max(c) for each day-group
dt <- dt[, `:=`(N = .N, mc = max(c)), by=day]
setkey(dt, "N")
# filter by maximum of N
dt <- dt[J(max(N))]
setkey(dt, "mc")
# settle ties with maximum of c
dt <- dt[J(max(mc))]
dt[, c("N", "mc", "day") := NULL]
print(dt)

#                   Date  c
# 1: 2012-12-07 05:00:00  0
# 2: 2012-12-07 06:00:00  3
# 3: 2012-12-07 07:00:00 10
# 4: 2012-12-07 08:00:00  6
于 2013-02-11T13:17:49.233 回答
4

这是一个解决方案tapply

# count rows per day and find maximum c value
res <- with(df1, tapply(c, as.Date(Date), function(x) c(length(x), max(x))))

# order these two values in decreasing order and find the associated day
# (at top position):
maxDate <- names(res)[order(sapply(res, "[", 1), 
                            sapply(res, "[", 2), decreasing = TRUE)[1]]

# subset data frame:
subset(df1, as.character(as.Date(Date)) %in% maxDate)

                  Date  c
7  2012-12-07 05:00:00  0
8  2012-12-07 06:00:00  3
9  2012-12-07 07:00:00 10
10 2012-12-07 08:00:00  6
于 2013-02-11T13:26:02.970 回答
3

为了完整起见,这里有一个plyr

library(plyr)
df1$day <- strftime(df1$Date, "%d/%m/%Y")
tmp <- ddply(df1[,c("day","c")], .(day), summarize, nb=length(c), max=max(c))
tmp <- tmp[order(tmp$nb, tmp$max, decreasing=TRUE),]
df1[df1$day==tmp$day[1],]

这使 :

                  Date  c        day
7  2012-12-07 05:00:00  0 07/12/2012
8  2012-12-07 06:00:00  3 07/12/2012
9  2012-12-07 07:00:00 10 07/12/2012
10 2012-12-07 08:00:00  6 07/12/2012
于 2013-02-11T13:33:27.663 回答