First, your function syfun
has to return NA
if there is no match. Hence, I added a line at the top of the function:
syfun <- function (x, y){
sxy <- NA
if(x == "AA" & y == "AA" | x == "BB" & y == "AA"){
sxy = 1
}
if(x == "AA" & y == "AB" | x == "AB" & y == "AA"){
sxy = 0.5
}
if (x == "AA" & y == "BB"| x == "BB" & y == "AA"){
sxy = 0
}
return(sxy)
}
Second, you can use outer
to apply the function to all combinations. You need to use Vectorize
to vectorize the function:
mat <- outer(names(dat), names(dat), function(x, y)
Vectorize(function(a, b) mean(Vectorize(syfun)(dat[[a]], dat[[b]])))(x,y))
Third, replace the elements on the diagonal with 1
:
diag(mat) <- 1
Fourth, set row and column names:
dimnames(mat) <- list(names(dat), names(dat))
The result:
A1 B1 C1
A1 1.00 0.25 0.5
B1 0.25 1.00 NA
C1 0.50 NA 1.0