Here is my small data set, and here is the function:
dat <- data.frame (
A1 = c("AA", "AA", "AA", "AA"),
B1 = c("BB", "BB", "AB", "AB"),
C1 = c("AB", "BB", "AA", "AB"))
Function
syfun <- function (x, y){
if(x == "AA" & y == "AA" | x == "BB" & y == "BB"){
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)
}
out <- rep (NA, NROW(dat))
for (i in 1:NROW(dat)){
out[i] <- syfun (dat[i,1], dat[i,1])
}
mean(out)
1
Here, what I'm trying to do is apply a function with the first column (variable A) with the same variable (variable A1) and average the output value. I want to save this output in a matrix cell.
Similarly between A1 and B1.
for (i in 1:NROW(dat)){
out[i] <- syfun (dat[i,1], dat[i,2])
}
mean(out)
0.25
Now, like a correlation matrix, I want to save all possible combination between a variable to make such a matrix.
A1 B1 C1
A1 1.0 0.25 0.5
B1 0.25 1.0 NA
C1 0.5 NA 1.0
Editing: A more complete function that does not create NA
syfun <- function (x, y){
sxy <- NA
if(x == "AA" & y == "AA" | x == "BB" & y == "BB"){
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
}
if (x == "BB" & y == "AB"| x == "AB" & y == "BB"){
sxy = 0.5
}
if(x == "AB" & y == "AB") {
sxy = 0.5
}
return(sxy)
}