[英]R aggregate based on multiple columns and then merge into dataframe?
我有一個數據框,看起來像:
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 df,但實際上有很多類型和第3列也必須類似地進行過濾,這是不實際的。 。
謝謝!
我們可以使用data.table
。 將'data.frame'轉換為'data.table'( setDT(df)
),按'id','type'(或帶有'id')分組,對'date'進行order
,並分配( :=
)第一個“日期”元素作為“最早日期”列。
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))
注意:避免分兩步執行此操作,即獲取匯總輸出然后加入
您可以使用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) )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.