I am guessing this is a plink FAM format, and some individuals are missing a father or a mother, and we want to add missing parent for individuals that have at least one of the parent, if both missing then do not add parents.
# dummy fam data with missing parents
df1 <- read.table(text = "FID IID Father Mother Sex
1 1 0 2 1
1 2 0 0 2
1 3 0 2 1
1 4 0 2 2
2 1 3 0 1
2 2 3 0 2
2 3 0 0 1
3 1 0 0 1
4 1 0 0 1
4 2 0 0 2
4 3 1 2 2
4 4 1 2 2
", header = TRUE,
colClasses = "character")
Note, about dummy data:
- FID == 1 is missing a father
- FID == 2 is missing a mother
- FID == 3 is a single individual family with no parents
- FID == 4 is no missing parents
Task, add missing Father or Mother only if one of them is missing. i.e.: if both missing Father == 0 and Mother == 0, then do not add parents.
library(dplyr) # using dplyr for explicity of steps.
# update 0 to IID for missing Father and Mother with suffix f and m
df1 <-
df1 %>%
mutate(
FatherNew = if_else(Father == "0" & Mother != "0", paste0(Mother, "f", IID), Father),
MotherNew = if_else(Mother == "0" & Father != "0", paste0(Father, "m", IID), Mother))
# add missing Fathers
missingFather <- df1 %>%
filter(
FatherNew != "0" &
MotherNew != "0" &
!FatherNew %in% df1$IID) %>%
transmute(
FID = FID,
IID = FatherNew,
Father = "0",
Mother = "0",
Sex = "1") %>%
unique
# add missing Mothers
missingMother <- df1 %>%
filter(
FatherNew != "0" &
MotherNew != "0" &
!MotherNew %in% df1$IID) %>%
transmute(
FID = FID,
IID = MotherNew,
Father = "0",
Mother = "0",
Sex = "2") %>%
unique
# update new Father/Mother IDs
res <- df1 %>%
transmute(
FID = FID,
IID = IID,
Father = FatherNew,
Mother = MotherNew,
Sex = Sex)
# add missing Fathers/Mothers as new rows, and sort
res <- rbind(
res,
missingFather,
missingMother) %>%
arrange(FID, IID)
Result, check output
res
# FID IID Father Mother Sex
# 1 1 1 2f1 2 1
# 2 1 2 0 0 2
# 3 1 2f1 0 0 1
# 4 1 2f3 0 0 1
# 5 1 2f4 0 0 1
# 6 1 3 2f3 2 1
# 7 1 4 2f4 2 2
# 8 2 1 3 3m1 1
# 9 2 2 3 3m2 2
# 10 2 3 0 0 1
# 11 2 3m1 0 0 2
# 12 2 3m2 0 0 2
# 13 3 1 0 0 1
# 14 4 1 0 0 1
# 15 4 2 0 0 2
# 16 4 3 1 2 2
# 17 4 4 1 2 2