Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R加速平方矩阵的矢量化_R_Performance_Matrix_Regression_Symmetric - Fatal编程技术网

R加速平方矩阵的矢量化

R加速平方矩阵的矢量化,r,performance,matrix,regression,symmetric,R,Performance,Matrix,Regression,Symmetric,任何人都可以帮我加速一些代码: n = seq_len(ncol(mat)) # seq 1 to ncol(mat) sym.pr<-outer(n,n,Vectorize(function(a,b) { return(adf.test(LinReg(mat[,c(a,b)]),k=0,alternative="stationary")$p.value) })) LinReg定义为: # Performs linear regression via OLS LinReg=fun

任何人都可以帮我加速一些代码:

n = seq_len(ncol(mat)) # seq 1 to ncol(mat)
sym.pr<-outer(n,n,Vectorize(function(a,b) {
    return(adf.test(LinReg(mat[,c(a,b)]),k=0,alternative="stationary")$p.value)
}))
LinReg
定义为:

# Performs linear regression via OLS
LinReg=function(vals) {  
  # regression analysis
  # force intercept c at y=0
  regline<-lm(vals[,1]~as.matrix(vals[,2:ncol(vals)])+0)

  # return spread (residuals)
  return(as.matrix(regline$residuals))
}
#通过OLS执行线性回归
LinReg=函数(VAL){
#回归分析
#y=0时的力截距c

regline从一些虚拟数据开始

mdf <- data.frame( x1 = rnorm(5), x2 = rnorm(5), x3 = rnorm(5) )
现在,您可以在行对上应用函数(为了简单起见,这里使用t.test):


谢谢@Beasterfield,这就成功了。对于对结果感兴趣的人:
600个15个变量的观测值:原始值:1.91s,优化(Beasterfield):0.86s
600对300个变量的观测值:原始:733s,优化:359s
。因此,
2x ~
的加速,非常令人印象深刻!再次感谢。刚刚实现..
2x
加速,因为它可以完成一半的计算量哈哈!@Ubobobo我认为这是整个想法,通过只计算上三角矩阵:-D
mdf <- data.frame( x1 = rnorm(5), x2 = rnorm(5), x3 = rnorm(5) )
pairs <- as.data.frame( t( combn( colnames( mdf  ),2 ) ) )
pairs
  V1 V2
1 x1 x2
2 x1 x3
3 x2 x3
pairs[["p.value"]] <- apply( pairs, 1, function( i ){
  t.test( mdf[i] )[["p.value"]]
})
pairs
  V1 V2   p.value
1 x1 x2 0.5943814
2 x1 x3 0.7833293
3 x2 x3 0.6760846
library(reshape2)
acast( pairs, V1 ~ V2 )
          x2        x3
x1 0.5943814 0.7833293
x2        NA 0.6760846