解决方案使用aggregate
:
aggregate(df$CPU, by=list(df$Date, df$Server), max)
# Group.1 Group.2 x
# 1 1/1/2012 WebA 30
# 2 1/2/2012 WebA 60
# 3 1/1/2012 WEbB 30
使用data.table
require(data.table)
dt <- data.table(df)
setkey(dt, "Date", "Server")
dt[, list(CPU.max = max(CPU)), by="Date,Server"]
# Date Server CPU.max
# 1: 1/1/2012 WebA 30
# 2: 1/1/2012 WEbB 30
# 3: 1/2/2012 WebA 60
编辑:按照 OP 的评论要求更多列:
df <- structure(list(Date = structure(c(1L, 1L, 1L, 2L, 2L, 2L),
.Label = c("1/1/2012", "1/2/2012"), class = "factor"),
Server = structure(c(1L, 1L, 2L, 1L, 1L, 1L),
.Label = c("WebA", "WEbB"), class = "factor"),
CPU = c(30L, 25L, 30L, 45L, 50L, 60L),
val1 = c(5L, 2L, 6L, 3L, 1L, 4L),
val2 = c(5L, 3L, 6L, 4L, 1L, 2L),
val3 = c(1L, 2L, 4L, 3L, 6L, 5L)),
.Names = c("Date", "Server", "CPU", "val1", "val2", "val3"),
row.names = c(NA, -6L), class = "data.frame")
> df
# Date Server CPU val1 val2 val3
# 1 1/1/2012 WebA 30 5 5 1
# 2 1/1/2012 WebA 25 2 3 2
# 3 1/1/2012 WEbB 30 6 6 4
# 4 1/2/2012 WebA 45 3 4 3
# 5 1/2/2012 WebA 50 1 1 6
# 6 1/2/2012 WebA 60 4 2 5
解决方案使用aggregate
:使用带有公式的聚合(如下所示)通常更好,因为 1)它保留列名,2)它干净且易于理解,3)它允许更容易合并以恢复其他列(由于(1 )) (这是你的问题,如果我猜对了)。
df.agg <- aggregate(data = df, CPU ~ Date + Server, max)
merge(df.agg, df)
# Date Server CPU val1 val2 val3
# 1 1/1/2012 WebA 30 5 5 1
# 2 1/1/2012 WEbB 30 6 6 4
# 3 1/2/2012 WebA 60 4 2 5
解决方案使用data.table
:
dt <- data.table(df, key=c("Date", "Server"))
# .SD holds the data.frame of the current group that is processed
dt[, .SD[which.max(CPU)], by=c("Date", "Server")]
# Date Server CPU val1 val2 val3
# 1: 1/1/2012 WebA 30 5 5 1
# 2: 1/1/2012 WEbB 30 6 6 4
# 3: 1/2/2012 WebA 60 4 2 5