按因子级别汇总,将其他变量保留在结果数据框中

时间:2013-04-26 01:16:26

标签: r

我正在尝试为每个因子级别计算数字列的最小值,同时在结果数据框中保留另一个因子的值。

# dummy data
dat <- data.frame(
    code = c("HH11", "HH45", "JL03", "JL03", "JL03", "HH11"), 
    index = c("023434", "3377477", "3388595", "3377477", "1177777", "023434"), 
    value = c(24.1, 37.2, 78.9, 45.9, 20.0, 34.6)
    )

我想要的结果是每个value级别的code最小值,并在结果数据框中保留index

# result I want:
#   code value    index
# 1 HH11  24.1   023434
# 2 HH45  37.2  3377477
# 3 JL03  20.0  1177777


# ddply attempt
library(plyr)
ddply(dat, ~ code, summarise, val = min(value))
#   code   val
# 1 HH11  24.1
# 2 HH45  37.2
# 3 JL03  20.0


# base R attempt
aggregate(value ~ code, dat, min)
#   code value
# 1 HH11  24.1
# 2 HH45  37.2
# 3 JL03  20.0

5 个答案:

答案 0 :(得分:16)

您需要对merge和原始aggregate

的结果使用data.frame
merge(aggregate(value ~ code, dat, min), dat, by = c("code", "value"))
##   code value   index
## 1 HH11  24.1  023434
## 2 HH45  37.2 3377477
## 3 JL03  20.0 1177777

答案 1 :(得分:3)

只是为了表明总是有多种方法可以给猫皮肤涂抹:

使用ave获取每个组中最小行的索引:

dat[which(ave(dat$value,dat$code,FUN=function(x) x==min(x))==1),]

#  code   index value
#1 HH11  023434  24.1
#2 HH45 3377477  37.2
#5 JL03 1177777  20.0

此方法还具有在多个值最小的情况下每个code组返回多行的潜在好处。

另一种使用by的方法:

do.call(rbind,
  by(dat, dat$code, function(x) cbind(x[1,c("code","index")],value=min(x$value)))
)
#      code   index value
# HH11 HH11  023434  24.1
# HH45 HH45 3377477  37.2
# JL03 JL03 3388595  20.0

答案 2 :(得分:1)

使用dplyrdata.table个包,您可以执行以下操作。您可以获取每个组具有最小值的行的索引。如果您使用slice(),则可以在dplyr中使用该功能。如果您使用.SD,则可以使用data.table实现相同的子集。

library(dplyr)
library(data.table)

dat %>%
group_by(code) %>%
slice(which.min(value))

#    code   index value
#  <fctr>  <fctr> <dbl>
#1   HH11  023434  24.1
#2   HH45 3377477  37.2
#3   JL03 1177777  20.0

setDT(dat)[, .SD[which.min(value)], by = code]

#   code   index value
#1: HH11  023434  24.1
#2: HH45 3377477  37.2
#3: JL03 1177777  20.0

答案 3 :(得分:0)

嗯,几分钟的搜索会让我在那里...... this answer似乎可以解决问题:

merge(dat, aggregate(value ~ code, dat, min))

答案 4 :(得分:0)

如果您已添加了可以完成它的索引变量。

library(plyr)

# ddply
ddply(dat, .(code,index), summarise, val = min(value))

# base R
aggregate(value ~ code + index, dat, min)
相关问题