Applying a function to every combination of two columns in a dataframe using R -
i want apply function myfoo
to every possible combination of 2 columns in dataframe mydf
, result in matrix format myoutput
.
consider following dataframe,
# example dataframe mydf <- data.frame(var1 = 1:10, var2 = 11:20, var3 = 21:30) head(mydf) # var1 var2 var3 # 1 11 21 # 2 12 22 # 3 13 23 # 4 14 24 # 5 15 25
to want apply following function every possible combination of 2 columns,
# example function myfoo <- function(vara, varb) sum(vara * varb) myfoo(var1, var2) # [1] 935
in order output.
# desired output myoutput <- matrix(c(0, 935, 1485, 935, 0, 4035, 1485, 4035, 0), 3, dimnames = list(names(mydf), names(mydf))) myoutput # var1 var2 var3 # var1 0 935 1485 # var2 935 0 4035 # var3 1485 4035 0
in case convert matrix (no reason keep data.frame
when columns of numeric class) , run compiled crossprod
function matrix cross product.
m <- as.matrix(mydf) res <- crossprod(m, m) diag(res) <- 0 # can skip part res # var1 var2 var3 # var1 0 935 1485 # var2 935 0 4035 # var3 1485 4035 0
Comments
Post a Comment