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

后端 未结 2 1897
無奈伤痛
無奈伤痛 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:56

    Using a for loop in R is rarely the right choice - especially when it comes to tasks involving manipulating data frames. R provides a whole lot of vectorized functions which can be used to accomplish most of the things you might want to use a loop for. And while you won't see the point at first (performance advantages of loops aren't really noticeable for small data sets on modern computers) learning to think with vectors instead of loops will long term help you to get a lot more out of using the language than trying to speak R with a C accent by using loops all the time.

    For example: one way to accomplish your particular task is to hack something together using a custom function and sapply:

    A <- data.frame(1:10, 2:11, 3:12)
    B <- data.frame(1:3, 4:6, 7:9)
    
    f <- function(i) {
      return(colSums(A[i:(i+2),] * B))
    }
    
    C <- sapply(1:(nrow(A) - 2), f)
    t(C)
    

    Sample output:

    > A
       X1.10 X2.11 X3.12
    1      1     2     3
    2      2     3     4
    3      3     4     5
    4      4     5     6
    5      5     6     7
    6      6     7     8
    7      7     8     9
    8      8     9    10
    9      9    10    11
    10    10    11    12
    > B
      X1.3 X4.6 X7.9
    1    1    4    7
    2    2    5    8
    3    3    6    9
    > t(C)
         X1.10 X2.11 X3.12
    [1,]    14    47    98
    [2,]    20    62   122
    [3,]    26    77   146
    [4,]    32    92   170
    [5,]    38   107   194
    [6,]    44   122   218
    [7,]    50   137   242
    [8,]    56   152   266
    

    If you're new to R, I definitely recommend reading up on the whole apply family of functions - they're endlessly useful.

提交回复
热议问题