R 查找每个 ID 的最大日期并创建具有最大日期的另一个字段的最大值的文件

R find max date per ID and create filed with maximum vale of another fild for the max date

我正在尝试创建一个字段 (maxKat),它根据另一列基于最大日期填充值。

示例代码:

a=c("RM", "kat", "Month")
RM=c("c1234","c1234","c1234", "c12345")
kat=as.integer(c("103","101","102", "145"))
Month=as.integer(c("201710","201711","201712", "201710"))
test=data.frame(RM,kat,Month)
names(test)=a


test2=aggregate(test[c("Month")], by=list(test$RM), max)
names(test2)=c("RM", "Monthmax")

test=merge(test,test2, by="RM")
test$maxkat=ifelse(test$Month==test$Monthmax, test$kat, NA)

我在这里计算最大日期,然后合并回主数据集(测试)。我想创建一个名为 maxkat 的新字段 取基于条件的 kat 的最大值,日期与 maxdate 匹配。

结果如下:

      RM kat  Month Monthmax maxkat
1  c1234 103 201710   201712     NA
2  c1234 101 201711   201712     NA
3  c1234 102 201712   201712    102
4 c12345 145 201710   201710    145

非常感谢任何有关如何用所需值填充 Null 的反馈。

整个数据集的期望结果是:

      RM kat  Month Monthmax maxkat
1  c1234 103 201710   201712    102
2  c1234 101 201711   201712    102
3  c1234 102 201712   201712    102
4 c12345 145 201710   201710    145

这会产生预期的结果:

RM=c("c1234","c1234","c1234", "c12345")
kat=as.integer(c("103","101","102", "145"))
Month=as.integer(c("201710","201711","201712", "201710"))
test=data.frame(RM,kat,Month)


test2=aggregate(test["Month"], by=list(test$RM), max)
names(test2)=c("RM", "Monthmax")
test2$maxkat <- test$kat[test$Month == test2$Monthmax]
(test=merge(test,test2, by="RM"))
#       RM kat  Month Monthmax maxkat
# 1  c1234 103 201710   201712    102
# 2  c1234 101 201711   201712    102
# 3  c1234 102 201712   201712    102
# 4 c12345 145 201710   201710    145

这里的策略是在合并之前将maxkat变量添加到test2数据框,并在test$Month等于test2$Monthmax时以test$kat的值作为基础。您正在比较不同维度的数据帧之间的值,但是因为 test2 是通过找到 Month 的最大值而精确创建的,所以您将得到完全正确的长度对象以放入 test2。然后你将它合并回测试中。