【发布时间】:2016-02-12 11:25:18
【问题描述】:
如何使用应用类型函数之一循环函数中的参数以使 R 中的代码更快?例如,我创建了一个函数来计算三个随机变量的联合互信息
### Function to loop over: Joint Mutual Information I({x_1,x_2};y)
library(infotheo)
JMI <-function(x1,x2,y){
entropy(cbind(x1,x2),method="emp") + entropy(y, method="emp") -
entropy(cbind(x1,x2,y),method="emp")
}
假设我有两个矩阵 (x1, x2) 和一个向量 y,例如:
#### randomly generate binary variables from a bernoulli distribution
set.seed(12345)
f1 <- rbinom(n=300,size=1,prob=0.5)
f2 <- rbinom(n=300,size=1,prob=0.5)
f3 <- rbinom(n=300,size=1,prob=0.5)
## creat y using xor operation of the two feature: x1 XOR x2
# this mean that y is 1 if f1[i]!=f2[i] and 0 otherwise
y <- ifelse(f1==f2,0,1)
x1 <-cbind(f1,f2)
x2 <- cbind(x1,f3)
现在,我想在 JMI 函数中循环 x1 和 x2。使用 for 循环看起来像这样:
# a length(x1) x length(x2)-Matrix with zeros
jmi <- matrix(rep(0,ncol(x2)*ncol(x1)),
nrow=ncol(x1),ncol=ncol(x2))
#### For loops to be avoided
for(i in 1:ncol(x1)){
for(j in 1:ncol(x2)){
jmi[i,j] <- JMI(x1[,i],x2[,j],y)
}#end out for(j)
}#end inner for(i)
有没有一种简单的方法可以避免两个 for 循环?
【问题讨论】:
-
我认为您在最后一个代码部分中混淆了行和列。当你定义
jmi时,你使用nrow = ncol(x2),但是在循环中,行索引i会超过1:ncol(x1)。 -
编辑不够。现在问题出现在对
JMI的调用中:i 运行在x2的列上,但用于获取x1的列(反之亦然)。请在发布之前运行您的代码。一旦你发布了一个工作示例,我会更新我的解决方案。 -
很抱歉,代码在我的电脑上运行良好。 i 在 x1 的列上运行并在 x1 中使用,对于 x2 也是如此
-
在您最后一次编辑之后,它确实运行良好。感谢您的更正。
标签: r performance for-loop apply mapply