我猜这是plink FAM 格式,有些人缺少父亲或母亲,我们想为至少有一个父母的人添加缺少的父母,如果两者都缺失,则不要添加父母。
# 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")
注意,关于虚拟数据:
- FID == 1 缺少父亲
- FID == 2 缺少母亲
- FID == 3 是一个没有父母的单身家庭
- FID == 4 不缺父母
任务,仅在其中一个缺失的情况下添加缺失的父亲或母亲。即:如果缺少父亲 == 0 和母亲 == 0,则不要添加父母。
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)
结果,检查输出
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