R中的不对称eta方阵

时间:2015-03-25 12:57:53

标签: r matrix correlation

我有一个函数来计算定性和定量变量之间相关性的eta平方系数:

eta <- function(x,y){
  m <- mean(x,na.rm = TRUE)
  sct <- sum((x-m)^2,na.rm = TRUE)
  n <- table(y)
  mk <- tapply(x,y,mean)
  sce <- sum(n*(mk-m)^2)
  return(ifelse(sct>0,sce/sct,0))
}

想象一下,我有以下变量(只是一个例子),其中缺少值:

a <-  factor(c("M","NA","F","F","NA","M","F"))
b <-  factor(c("y","y","y","n","n","n","y")
d <- c(2,5,4,8,9,6,4)
e <- c(5,7,8,5,6,9,7) 

我需要编写一个函数,为定性和定量变量x和y的每个组合返回一个带有eta系数的矩阵。 这样的事情可能(它不起作用):

 matrix<-function(x,y){
  col.y<-ncol(y)
  row.x<-nrow(x)
  M<-matrix(ncol=col.y,nrow=row.x,dimnames = list(names(x), names(y)))
  for(i in 1:col.y){
    for(j in 1:row.x){
      M[i,j]<-rap.corr(y[,i],x[,j])
    }
  }
  return(M)
}

我该怎么做?提前谢谢..

1 个答案:

答案 0 :(得分:1)

您可以使用mapply

执行此操作
qual = list(a=a, b=b)
quant = list(e=e,d=d)

m = matrix(mapply(eta, rep(quant, length(qual)), rep(qual, each=length(quant))), ncol=length(qual))

rownames(m) = names(quant)
colnames(m) = names(qual)

#> m
#           a            b
#e 0.01950355 0.0008865248
#d 0.25333333 0.7363333333