从函数外部获取列中的值

时间:2015-11-16 04:35:01

标签: r

我试图将行的值传递给outer。我错过了什么?

#create dataframe as example that will work for this function
exampledf<- matrix(ceiling(runif(16,0,50)), ncol=4)
colnames(exampledf)<-c("col1","col2","col3","col4")
x<-as.data.frame(exampledf)
cols<-cbind(colnames(x))
#end creating variables

  matr<-outer(cols,cols,function(a,b){
    return(eval(parse(text = "x$a")))#Doesnt work
    })

我的最终目标是获得部分相关矩阵。函数spcor.test()接受两个向量(不是我试图给它的数据帧)。我正在尝试编写一个采用数据帧的版本。

到目前为止我的所有代码:

library(matrixcalc)
library(ppcor)
exampledf<- matrix(ceiling(runif(16,0,50)), ncol=4)
while(is.singular.matrix(exampledf)!=TRUE){
  exampledf<- matrix(ceiling(runif(16,0,50)), ncol=4)
}
colnames(exampledf)<-c("col1","col2","col3","col4")

#single example
#spcor.test(exampledf[,1],exampledf[,2],exampledf[,3])

x<-as.data.frame(exampledf)
cont<-"col3"
#semiCorr<-function(x,cont){ #x=dataframe to correlate, z=names of variables to control for
  library(ppcor)
  cols<-cbind(colnames(x))
  cols<-cols[-c(grep(cont,cols))]
  matr<-outer(cols,cols,function(a,b){
    get(x$a)
    #spcor.test(eval(parse(text = "x$a")),eval(parse(text = "x$b")),x[,c(cont)])
    })
  return((matr)) #return a matrix of the semipartial correlations
#}
#semiCorr(exampledf,"col3")

  cols<-cols[-c(grep(cont,cols))]
  matr<-outer(cols,cols,function(a,b){
    return(a)
    #return(eval(parse(text = "x$a")))#Doesnt work
  })

1 个答案:

答案 0 :(得分:0)

我们可以将expand.gridapply

一起使用
apply(expand.grid(cols, cols), 1, FUN= function(cols) x[cols])