Your outcome is a bit strange. I would create a parent data.frame and just add new records to that one, and copy the parentid to the other data. Not introduce duplicates in a parent data.frame. Below is something you could use.
step1: create parent data.frame from your initial data.frame (df1)
library(dplyr)
parents <- df1 %>%
# remove dublicates.
unique() %>%
mutate(ParentId = row_number())
PatientID Name DOB SEX ParentId
1 1000017863 awssV 04-01-1936 F 1
2 1000017898 wrafdU 21-03-1971 M 2
3 1000017947 asfadfdV 29-04-1949 F 3
4 1000018029 dgdbcASK 28-12-1953 F 4
5 1000018164 adcv K 22-05-1952 M 5
6 1000018181 asfvvR 12-06-1956 M 6
step2: adding new records to parent data.frame
parents <- df2 %>%
# remove dublicates
unique() %>%
anti_join(parents) %>%
# add new rows on the bottom of parents
bind_rows(parents, .) %>%
mutate(ParentId = ifelse(is.na(ParentId), row_number(), ParentId))
PatientID Name DOB SEX ParentId
1 1000017863 awssV 04-01-1936 F 1
2 1000017898 wrafdU 21-03-1971 M 2
3 1000017947 asfadfdV 29-04-1949 F 3
4 1000018029 dgdbcASK 28-12-1953 F 4
5 1000018164 adcv K 22-05-1952 M 5
6 1000018181 asfvvR 12-06-1956 M 6
7 1000020202 asdf 05-05-1966 F 7 #<<< new record
step3: add parentid to original data is simply using an inner_join.
df1 %>% inner_join(parents)
Joining, by = c("PatientID", "Name", "DOB", "SEX")
PatientID Name DOB SEX ParentId
1 1000017863 awssV 04-01-1936 F 1
2 1000017898 wrafdU 21-03-1971 M 2 #<<<< duplicate entries, same parentid.
3 1000017947 asfadfdV 29-04-1949 F 3
4 1000018029 dgdbcASK 28-12-1953 F 4
5 1000017898 wrafdU 21-03-1971 M 2 #<<<< duplicate entries, same parentid.
6 1000018164 adcv K 22-05-1952 M 5
7 1000018181 asfvvR 12-06-1956 M 6
data:
df1 <- structure(list(PatientID = c(1000017863L, 1000017898L, 1000017947L,
1000018029L, 1000017898L, 1000018164L, 1000018181L),
Name = c("awssV","wrafdU", "asfadfdV", "dgdbcASK", "wrafdU", "adcv K", "asfvvR"),
DOB = c("04-01-1936", "21-03-1971", "29-04-1949", "28-12-1953",
"21-03-1971", "22-05-1952", "12-06-1956"),
SEX = c("F", "M", "F", "F", "M", "M", "M")),
class = "data.frame", row.names = c(NA, -7L))
df2 <- structure(list(PatientID = c(1000017863L, 1000017898L, 1000020202L),
Name = c("awssV", "wrafdU", "asdf"),
DOB = c("04-01-1936", "21-03-1971", "05-05-1966"),
SEX = c("F", "M", "F")),
class = "data.frame", row.names = c(NA, -3L))