验证序列正在增加

问题描述 投票:0回答:1

我有大约 10,000 条记录的数据集。它包含大约 3,000 个唯一 ID,每个 ID 有 2 行以上带有关联变量的行。

我需要检查的是预期的 1 岁年龄进展相对于其他变量之一的日期是否有意义。 (我没有出生日期)。

例如

正确

身份证 样本_日期 年龄
123456 2023年4月7日 47
123456 2023年11月15日 47
123456 2024年8月2日 48

不正确

身份证 样本_日期 年龄
123456 2023年4月7日 47
123456 2023年11月15日 47
123456 2024年8月2日 46

我有源代码(来自堆栈溢出文本),可以识别相对于身份证号码的年龄不匹配,该代码效果很好。

library(data.table)
setDT(df)

#get the gender of the final observation for each ID
df[df[,Sex[.N],by=ID], recent_Sex:=(i.V1), on="ID"]

#find if there are any mismatches by ID
df[,mismatch:=any(recent_Sex!=Sex), by=ID]

年龄差异大于 1 岁的数量很少,而且很容易检查。然而,只有 1 年的年龄差异大约有 3,000 条记录,我正在寻找一种快速方法来检查这些记录是否正常,而不必检查每一行!

r date sequence
1个回答
0
投票

也许你可以试试这个

setDT(df)
df[
    ,
    mismatch := var(as.integer(format(as.IDate(sample_date, format = "%d/%m/%Y"), "%Y")) - age) == 0, 
    ID
][]

这给出了

       ID sample_date   age mismatch
    <int>      <char> <int>   <lgcl>
1: 123456  04/07/2023    47     TRUE
2: 123456  15/11/2023    47     TRUE
3: 123456  08/02/2024    48     TRUE

数据

> dput(df)
structure(list(ID = c(123456L, 123456L, 123456L), sample_date = c("04/07/2023",
"15/11/2023", "08/02/2024"), age = c(47L, 47L, 48L)), class = "data.frame", row.names = c(NA,
-3L))
© www.soinside.com 2019 - 2024. All rights reserved.