How to create a for loop in R for this peculiar calculation

后端 未结 2 1888
無奈伤痛
無奈伤痛 2021-01-23 01:15

I can\'t figure out with this (apparently) simply kind of operation:

Given these two diferent dataframes df(A) (nrow=10,ncol=3) and df(B) (nrow

2条回答
  •  既然无缘
    2021-01-23 01:36

    As an alternative to user164385's answer, which is very good, you can also use the following loop that will do the trick (even though they're not always optimal, loops can make it easier when beginning with R). Note that with all-numeric data, you can use matrices instead of dataframes:

    A <- matrix(c(1,2,4,3,5,7,5,7,6,6,9,
                  5.9,9,11,8,4.5,5.5,7.9,
                  21,6.7,13.6,3.5,5,6,6,
                  7.9,1,67,4,2), ncol=3, byrow=T)
    B <- matrix(c(1,4,5,2,7,7,3,9,8), ncol=3, byrow=T)
    
    results <- matrix(nrow=8, ncol=3)
    for(i in 1:(nrow(A)-2)) {
      results[i,] <- colSums(A[i:(i+2),] * B)
    }
    results
          [,1]  [,2]  [,3]
    [1,]  22.0 106.0 117.0
    [2,]  31.0 150.0 124.2
    [3,]  44.0 190.0 135.3
    [4,]  37.5 162.5 148.7
    [5,]  81.0 142.8 204.1
    [6,]  57.0 113.9 182.7
    [7,]  46.0 132.9 118.0
    [8,] 216.5 111.3  53.0
    

提交回复
热议问题