我有一个数据集,想要删除具有相同患者ID,药物,剂量和Start.date的行,但是其中一个具有结束日期,而一个没有结束日期。我想用NA End.date删除该行。
ID First.name Last.name Report.year Medication Dosage Start.date End.date
1 John Doe 2013 Modulator A Dosage 1 2013-01-01 <NA>
1 John Doe 2013 Modulator A Dosage 2 2013-01-01 <NA>
1 John Doe 2016 Modulator B Dosage 1 2016-01-01 <NA>****REMOVE
1 John Doe 2018 Modulator B Dosage 1 2016-01-01 2018-12-31
1 John Doe 2019 Modulator C <NA> 2019-01-01 <NA>****REMOVE
1 John Doe 2020 Modulator C Dosage 1 2019-01-01 <NA>
1 John Doe 2021 Modulator C <NA> 2019-01-01 2021-12-31
最终结果应该是:
ID First.name Last.name Report.year Medication Dosage Start.date End.date
1 John Doe 2013 Modulator A Dosage 1 2013-01-01 <NA>
1 John Doe 2013 Modulator A Dosage 2 2013-01-01 <NA>
1 John Doe 2018 Modulator B Dosage 1 2016-01-01 2018-12-31
1 John Doe 2020 Modulator C Dosage 1 2019-01-01 <NA>
1 John Doe 2021 Modulator C <NA> 2019-01-01 2021-12-31
我尝试了以下代码,但是它一起删除了所有结束日期。
data %>%
group_by(Patient.ID, Medication, Dosage, Start.date) %>%
filter(n_distinct(End.date)==1) %>%
distinct()
在Base-R中。这将重新排列数据的顺序,以确保保留End.dates!= NA的行。 c(1,5,6,7)
确定要检查重复的列。
df <- df[order(df$End.date),]
df[!duplicated(apply(df[,c(1,5,6,7)],1,data.frame)),]
ID First.name Last.name Report.year Medication Dosage Start.date End.date
4 1 John Doe 2018 ModulatorB Dosage1 2016-01-01 2018-12-31
7 1 John Doe 2021 ModulatorC <NA> 2019-01-01 2021-12-31
1 1 John Doe 2013 ModulatorA Dosage1 2013-01-01 <NA>
2 1 John Doe 2013 ModulatorA Dosage2 2013-01-01 <NA>
6 1 John Doe 2020 ModulatorC Dosage1 2019-01-01 <NA>
示例数据:
df <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L), First.name = c("John",
"John", "John", "John", "John", "John", "John"), Last.name = c("Doe",
"Doe", "Doe", "Doe", "Doe", "Doe", "Doe"), Report.year = c(2018L,
2021L, 2013L, 2013L, 2016L, 2019L, 2020L), Medication = c("ModulatorB",
"ModulatorC", "ModulatorA", "ModulatorA", "ModulatorB", "ModulatorC",
"ModulatorC"), Dosage = c("Dosage1", NA, "Dosage1", "Dosage2",
"Dosage1", NA, "Dosage1"), Start.date = c("2016-01-01", "2019-01-01",
"2013-01-01", "2013-01-01", "2016-01-01", "2019-01-01", "2019-01-01"
), End.date = c("2018-12-31", "2021-12-31", NA, NA, NA, NA, NA
)), row.names = c(4L, 7L, 1L, 2L, 3L, 5L, 6L), class = "data.frame")