繁体   English   中英

从函数和两个数字数据框创建矩阵

[英]Create a matrix from a function and two numeric data frames

我正在尝试在R中创建各种距离/关联函数的矩阵。我有一个类似于cor的函数,它给出了两个向量之间的关联。 现在我想采用数字向量的数据帧(或矩阵),比如mtcars ,并从函数和数据框创建一个矩阵。 我认为这是outer东西,但我没有让它发挥作用。 这是使用cor和mtcars的尝试。

cor(mtcars$mpg, mtcars$cyl)  #a function that gives an association between two vectors                  
outer(mtcars, mtcars, "cor") #the attempt to create a matrix of all vectors in a df

是的我知道cor可以直接做到这一点,让我们假装它不能。 cor只是找到两个向量之间的相关性。

所以最终的目标是获得你从cor(mtcars)获得的矩阵。

先感谢您。

您可以使用带有列名称或列号作为参数的函数的outer

outer(
  names(mtcars), 
  names(mtcars), 
  Vectorize(function(i,j) cor(mtcars[,i],mtcars[,j]))
)

outer并不直接取决于工作。 它只会扩展其XY向量并调用cor一次。 编辑正如@Vincent Zoonekynd所示,您可以使其适应工作。

否则,一个相当简单的循环就可以了:

m <- as.matrix(mtcars)
r <- matrix(1, ncol(m), ncol(m), dimnames=list(colnames(m), colnames(m)))
for(i in 1:(ncol(m)-1)) {
  for(j in (i+1):ncol(m)) {
     r[i,j] <- cor(m[,i], m[,j])
     r[j,i] <- r[i,j]
  }
}

all.equal(r, cor(m)) # Sanity check...

r # print resulting 11x11 correlation matrix

...这里我假设您的相关性是对称的,而cor(x,x)== 1

更新由于文森特的解决方案更优雅,我不得不反对我的速度快2倍的事实:-)

# Huge data frame (1e6 rows, 10 cols)
d <- data.frame(matrix(1:1e7, ncol=10))

# Vincent's solution    
system.time(outer(
  names(d), 
  names(d), 
  r <- Vectorize(function(i,j) cor(d[,i],d[,j]))
)) # 2.25 secs

# My solution    
system.time({
m <- d
r <- matrix(1, ncol(m), ncol(m), dimnames=list(colnames(m), colnames(m)))
for(i in 1:(ncol(m)-1)) {
  for(j in (i+1):ncol(m)) {
     r[i,j] <- cor(m[,i], m[,j])
     r[j,i] <- r[i,j]
  }
}
}) # 1.0 secs

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM