R聚合基于多个列,然后合并到数据框中?

时间:2017-01-10 02:54:53

标签: r merge aggregate

我的数据框如下:

id<-c(1,1,1,3,3)
date1<-c("23-01-08","01-11-07","30-11-07","17-12-07","12-12-08")
type<-c("A","B","A","B","B")
df<-data.frame(id,date,type)
df$date<-as.Date(as.character(df$date), format = "%d-%m-%y")

我想要的是添加一个新列,其中包含每种类型的每个ID的最早日期。第一次尝试工作正常,只根据ID进行聚合和合并。

d = aggregate(df$date, by=list(df$id), min)
df2 = merge(df, d, by.x="id", by.y="Group.1")

我想要的是按类型过滤并获得此结果:

data.frame(df2, desired=c("2007-11-30","2007-11-01", "2007-11-30","2007-12-17","2007-12-17"))

我尝试了很多可能性。我真的认为这可以通过列表完成,但我不知道如何......

d = aggregate(df$date, by=list(df$id, df$type), min)

# And merge the result of aggregate with the original data frame
df2 = merge(df,d,by.x=list("id","type"),by.y=list("Group.1","Group.2"))

对于这个简单的例子,我可以将类型分成他们自己的df,构建新的列,然后组合生成的2个dfs,但实际上有很多类型和第3列也需要同样过滤哪个不实用......

谢谢!

2 个答案:

答案 0 :(得分:2)

我们可以使用data.table。转换&#39; data.frame&#39;到&#39; data.table&#39; (setDT(df)),按&#39; id&#39;分组,&#39;类型&#39; (或使用&#39; id&#39;),order&#39; date&#39;并指定(:=)&#39; date&#39;的第一个元素。作为最早的日期&#39;列。

library(data.table)
setDT(df)[order(date), earliestdateid := date[1], by = id
    ][order(date), earliestdateidtype := date[1], by = .(id, type)]
df
#    id       date type earliestdateid earliestdateidtype
#1:  1 2008-01-23    A     2007-11-01         2007-11-30
#2:  1 2007-11-01    B     2007-11-01         2007-11-01
#3:  1 2007-11-30    A     2007-11-01         2007-11-30
#4:  3 2007-12-17    B     2007-12-17         2007-12-17
#5:  3 2008-12-12    B     2007-12-17         2007-12-17

dplyr类似的方法是

library(dplyr)
df %>%
   group_by(id) %>%
   arrange(date) %>%
   mutate(earliestdateid = first(date)) %>%
   group_by(type, add = TRUE) %>%
   mutate(earliestdateidtype = first(date))

注意:这样做可以分两步完成,即获得汇总输出然后加入

答案 1 :(得分:2)

您可以使用ave代替不同的组获得两个最小值:

df$minid <- with(df, ave(date, id, FUN=min, drop=TRUE) )
df$minidtype <- with(df, ave(date, list(id,type), FUN=min, drop=TRUE) )
df

#  id       date type      minid  minidtype
#1  1 2008-01-23    A 2007-11-01 2007-11-30
#2  1 2007-11-01    B 2007-11-01 2007-11-01
#3  1 2007-11-30    A 2007-11-01 2007-11-30
#4  3 2007-12-17    B 2007-12-17 2007-12-17
#5  3 2008-12-12    B 2007-12-17 2007-12-17

如果你很棘手,你也可以在一个电话中完成所有工作:

df[c("minid", "minidtype")] <- lapply(list("id", c("id","type")),
                                  FUN=function(x) ave(df$date, df[x], FUN=min, drop=TRUE) )