Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I want to calculate the data for every N rows (e.g. every 4 rows):

data

A <- c(1,4,5,7,8,10,3)

B <- c(2,4,1,8,9,2,5)

df <- data.frame(A,B)

What I want to do is averaging the data from A and B (every 4 rows) and divide both values. The desired output is:

A   B   Calc

1   2   1.133333333

4   4   1.090909091

5   1   1.5

7   8   1.166666667

8   9   1.3125

10  2   1.857142857

3   5   0.6

I can do the calculation easily in excel by performing that:

(AVERAGE(A2:A5))/(AVERAGE(B2:B5)) for the first row. The next row =(AVERAGE(A3:A6))/(AVERAGE(B3:B6)), and last row =(AVERAGE(A8:A11))/(AVERAGE(B8:B11)).

1 Answer

0 votes
by (108k points)

For that, you can use the zoo's rollapply() function to do this rolling prediction, in R programming:

library(zoo)

transform(df, Calc = rollapply(A, 4, align = 'left', mean, partial = TRUE)/

                     rollapply(B, 4, align = 'left', mean, partial = TRUE))

#   A B     Calc

#1  1 2 1.133333

#2  4 4 1.090909

#3  5 1 1.500000

#4  7 8 1.166667

#5  8 9 1.312500

#6 10 2 1.857143

#7  3 5 0.600000

Browse Categories

...