【问题标题】:Correlation with sliding window与滑动窗口的相关性
【发布时间】:2018-08-20 19:45:03
【问题描述】:

我想计算带有滑动窗口 (window=1) 的两个向量(每个四个元素)之间的 pearson 相关性并保持最佳结果:

list1 <- read.table(text= "20 
                           34
                           89
                           35")

list2 <- read.table(text= "22
                          99 
                          313 
                          13 
                          71 
                          200")

比较将是一个循环:

cor(x=c(20,34,89,35),y=c(22,99,313,13), method = "pearson")  
cor(x=c(20,34,89,35),y=c(99,313,13,71), method = "pearson")
cor(x=c(20,34,89,35),y=c(313,13,71,200), method = "pearson")

结果将包含得分和给出最高相关得分的向量。在这种情况下,它将是:x=c(20,34,89,35) and y=c(22,99,313,13)0.9588095

【问题讨论】:

    标签: r correlation sliding-window


    【解决方案1】:

    使用rollapply 计算相关性,找到最大的索引并从中推导出y 及其与x 的相关性。

    library(zoo)
    
    x <- list1$V1
    w <- length(x)
    ix <- which.max(rollapply(list2$V1, w, cor, x))
    y <- list2$V1[seq(ix, length = w)]
    
    y
    ## [1]  22  99 313  13
    
    cor(x, y)
    ## [1] 0.9588095
    

    上面的一个变体是从rollapply返回相关性和y向量:

    r <- rollapply(list2$V1, length(x), function(y) c(cor(x, y), y))
    ix <- which.max(r[, 1])
    
    r[ix, 1]
    ## [1] 0.9588095
    
    r[ix, -1]
    ## [1]  22  99 313  13
    

    【讨论】:

      【解决方案2】:

      R 基础解决方案

      out <- list(NULL)
      j <- 1
      ind <- 0
      while(ind[length(ind)]<length(list2$V1)){ 
        ind <- j:(j+3);
        out[[j]] <- list(Vector1=list1$V1, 
                      Vector2=list2$V1[ind],
                      Cor=cor(list1$V1, list2$V1[ind]));
        out
        j <- j+1
      }
      
      out[[which.max(unlist(sapply(out, "[", "Cor")))]]
      

      产生:

      $Vector1
      [1] 20 34 89 35
      
      $Vector2
      [1]  22  99 313  13
      
      $Cor
      [1] 0.9588095
      

      【讨论】:

        猜你喜欢
        • 2011-12-20
        • 2017-12-27
        • 2013-08-21
        • 2014-07-05
        • 1970-01-01
        • 1970-01-01
        • 2019-05-04
        • 1970-01-01
        • 2018-08-13
        相关资源
        最近更新 更多