Я думаю, вам понадобится вложенный ifelse
здесь
df[paste0("Sample", seq_along(5:ncol(df)), ".vd")] <- t(apply(df, 1, function(x)
ifelse(x[5:length(x)] == x["ref"], 0,
ifelse(x[5:length(x)] == x["het"], 1, 2))))
df
# SNP ref het risk Sample1 Sample2 Sample1.vd Sample2.vd
#1 rs1 GG AG AA AG GG 1 0
#2 rs2 AA AG GG AG AA 1 0
#3 rs3 AA AG GG AG AG 1 1
#4 rs4 GG AG AA AG AA 1 2
#5 rs5 GG AG AA AG AA 1 2
#6 rs6 GG AG AA AG AG 1 1
#7 rs7 AA AG GG AA AA 0 0
#8 rs8 CC AC AA AC CC 1 0
#9 rs9 GG AG AA GG GG 0 0
#10 rs10 GG AG AA GG AG 0 1
#....
Или, если вы хотите использовать его как функцию
VariantDetected <- function(x) {
ifelse(x[5:length(x)] == x["ref"], 0,
ifelse(x[5:length(x)] == x["het"], 1, 2))
}
df[paste0("Sample", seq_along(5:ncol(df)), ".vd")]<-t(apply(df, 1, VariantDetected))
data
df <- structure(list(SNP = structure(c(1L, 12L, 14L, 15L, 16L, 17L,
18L, 19L, 20L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 13L), .Label =
c("rs1",
"rs10", "rs11", "rs12", "rs13", "rs14", "rs15", "rs16", "rs17",
"rs18", "rs19", "rs2", "rs20", "rs3", "rs4", "rs5", "rs6", "rs7",
"rs8", "rs9"), class = "factor"), ref = structure(c(3L, 1L, 1L,
3L, 3L, 3L, 1L, 2L, 3L, 3L, 1L, 3L, 3L, 1L, 3L, 1L, 1L, 3L, 3L,
3L), .Label = c("AA", "CC", "GG"), class = "factor"), het =
structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L,
2L, 2L, 2L), .Label = c("AC", "AG"), class = "factor"), risk =
structure(c(1L,
3L, 3L, 1L, 1L, 1L, 3L, 1L, 1L, 1L, 3L, 1L, 1L, 3L, 1L, 2L, 3L,
1L, 1L, 1L), .Label = c("AA", "CC", "GG"), class = "factor"),
Sample1 = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 1L, 2L, 4L,
4L, 1L, 1L, 3L, 3L, 1L, 1L, 1L, 4L, 4L, 3L), .Label = c("AA",
"AC", "AG", "GG"), class = "factor"), Sample2 = structure(c(4L,
1L, 2L, 1L, 1L, 2L, 1L, 3L, 4L, 2L, 4L, 2L, 1L, 1L, 1L, 1L,
1L, 4L, 2L, 2L), .Label = c("AA", "AG", "CC", "GG"), class = "factor"),
Sample1.vd = c(1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 2, 1, 1,
2, 0, 0, 0, 0, 1), Sample2.vd = c(0, 0, 1, 2, 2, 1, 0, 0,
0, 1, 2, 1, 2, 0, 2, 0, 0, 0, 1, 1)), row.names = c(NA, -20L
), .Names = c("SNP", "ref", "het", "risk", "Sample1", "Sample2",
"Sample1.vd", "Sample2.vd"), class = "data.frame")