[英]Applying a function to every combination of two columns in a dataframe using R
I want to apply a function myfoo
to every possible combination of two columns in a dataframe mydf
and get the result in a matrix format myoutput
. 我想将函数
myfoo
应用于数据帧mydf
中两列的所有可能组合,并以矩阵格式myoutput
获得结果。
Consider the 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 which I want to apply the following function to every possible combination of two columns, 我想将以下功能应用于两列的每种可能的组合,
# Example function
myfoo <- function(varA, varB) sum(varA * varB)
myfoo(var1, var2)
# [1] 935
in order to get this 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 your case I would convert to a matrix (no reason to keep it a data.frame
when all columns are of numeric class) and just run the compiled crossprod
function which does a matrix cross product. 在你的情况我会转化为矩阵(没有理由保持它
data.frame
当所有列是数字类的),只是运行编译crossprod
功能,做一个矩阵积。
m <- as.matrix(mydf)
res <- crossprod(m, m)
diag(res) <- 0 # You can probably skip that part
res
# var1 var2 var3
# var1 0 935 1485
# var2 935 0 4035
# var3 1485 4035 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.