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
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
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.