【问题标题】:How to run all "N take 2" iterations of a function?如何运行函数的所有“N take 2”迭代?
【发布时间】:2017-05-12 03:54:59
【问题描述】:

我编写了一个简单的相关函数,它包含三个变量。 “A”和“B”是等长的数值向量,“n”是长度。

Corr.fxn <- function(A, B, n){
Correlation <- (sum((A - mean(A))*(B - mean(B))) / (n-1)) / (sd(A)*sd(B))
return(Correlation)
}

该函数运行良好,但我有很多向量要处理。修改此代码以处理我的向量集“N”的所有“N take 2”唯一分析的最佳方法是什么?

编辑:

显示向量结构的示例数据:

A <- c(-1, 0, 1, -1, 0, 1, -1, 0, 1)
B <- c(1, 1, -1, 0, 1, -1, 0, 0, 1)
...
n <- length(A)

假设我有向量 A 到 Z,我想修改我的代码以输出一个包含所有 {26 take 2} 相关值的新向量。

【问题讨论】:

  • 向量是如何组织的?制作一些示例输入数据并发布将很有用。
  • apply(combn(N, 2), 2, Corr.fxn)?如果N 是一个列表,则改为对其进行索引。
  • "N take 2" 让我想起了combn。如果您执行combn(N, 2, simplify = FALSE) 之类的操作,您将获得一个列表,其中每个元素都是您的两个N 向量的列表。以combn(list(1:2, 3:4, 5:6), 2, simplify = FALSE) 为例。 (你打败了我,阿利斯泰尔……)

标签: r


【解决方案1】:

假设您在列表v 中有一堆数字向量,这是一种可行的方法,如下所示:

v <- list()
for (i in 1:10) {
  v[[i]] <- sample(1:10, 10, replace = TRUE)
}

apply(combn(1:10, 2), 2, function(x) Corr.fxn(v[[x[1]]], v[[x[2]]], length(v[[x[1]]])))

【讨论】:

    【解决方案2】:

    在这个答案中,我假设了两件事。首先,您想自己编写一个函数,否则您可以使用Hmisc::rcorr。其次,您希望“N take 2”部分位于函数内部,否则前面建议的方法是正确的。在这种情况下,您可以这样做:

    Corr.fxn <- function(vectors, n){
        pairs<- combn(length(vectors), 2)
        npairs<- ncol(pairs)
        cor.mat<- matrix(NA, nrow = length(vectors), ncol = npairs)
        for (i in 1:ncol(pairs)){
            A<- vectors[[pairs[1, i]]]
            B<- vectors[[pairs[2, i]]]
        cor.mat[pairs[1, i], pairs[2, i]] <- (sum((A - mean(A))*(B - mean(B))) / (n-1)) /(sd(A)*sd(B))
        }
        cor.mat[lower.tri(cor.mat)]<- cor.mat[upper.tri(cor.mat)] ###
        diag(cor.mat)<- 1 ###
        cor.mat<- data.frame(cor.mat) ###
        row.names(cor.mat)<- colnames(cor.mat)<- names(vectors) ###
        return(cor.mat)
    }
    

    ### 结尾的行是出于装饰原因。主要输入是一个称为“向量”的列表。所以它的工作原理如下:

    A<- runif(100, 1, 100)
    B<- runif(100, 30, 50)
    C<- runif(100, 120, 200)
    > Corr.fxn(list(A=A, B=B, C=C), n=100)
               A           B           C
    A  1.0000000 -0.11800104 -0.13980458
    B -0.1180010  1.00000000  0.04933581
    C -0.1398046  0.04933581  1.00000000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 2015-10-08
      • 2021-02-17
      • 2023-02-22
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多