gpt4 book ai didi

r - 在多行的单列中查找最大日期

转载 作者:行者123 更新时间:2023-12-03 22:51:23 26 4
gpt4 key购买 nike

我有以下数据框:

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


id date date2
1 23-01-08 2008-01-23
1 01-11-07 2007-11-01
2 30-11-07 2007-11-30
3 17-12-07 2007-12-17
3 12-12-08 2008-12-12

现在我需要创建第四列并为每个 id 插入最大交易日期在那里面。
决赛 table 应如下:
id     date      date2        max
1 23-01-08 2008-01-23 2008-01-23
1 01-11-07 2007-11-01 0
2 30-11-07 2007-11-30 2007-11-30
3 17-12-07 2007-12-17 0
3 12-12-08 2008-12-12 2008-12-12

如果你能帮我解决这个问题,我将不胜感激。

最佳答案

id<-c(1,1,2,3,3)
date<-c("23-01-08","01-11-07","30-11-07","17-12-07","12-12-08")
df<-data.frame(id,date)
df$date2<-as.Date(as.character(df$date), format = "%d-%m-%y")
# aggregate can be used for this type of thing
d = aggregate(df$date2,by=list(df$id),max)
# And merge the result of aggregate
# with the original data frame
df2 = merge(df,d,by.x=1,by.y=1)
df2

id date date2 x
1 1 23-01-08 2008-01-23 2008-01-23
2 1 01-11-07 2007-11-01 2008-01-23
3 2 30-11-07 2007-11-30 2007-11-30
4 3 17-12-07 2007-12-17 2008-12-12
5 3 12-12-08 2008-12-12 2008-12-12

编辑:由于您希望当日期与最大日期不匹配时最后一列为“空”,因此您可以尝试下一行。
df2[df2[,3]!=df2[,4],4]=NA

df2
id date date2 x
1 1 23-01-08 2008-01-23 2008-01-23
2 1 01-11-07 2007-11-01 <NA>
3 2 30-11-07 2007-11-30 2007-11-30
4 3 17-12-07 2007-12-17 <NA>
5 3 12-12-08 2008-12-12 2008-12-12

当然,清理列名等总是很好的,但我把它留给你。

关于r - 在多行的单列中查找最大日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12127149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com