Alex_P
Alex_P

Reputation: 143

Dataframe Iterative calculations and merging in R

I have the following sample type of data frame with many rows and columns. I need to take the average of the previous rows and add it to the other column with loop in R.

Input:

MA1 MA2 MA3 MA4 MA5
4.0 0.2 0.2 0.2 0.2
3.0 4.0 0.2 3.0 0.2
0.2 0.2 0.2 0.2 0.2
0.2 4.0 1.0 0.2 2.0
0.2 0.2 0.2 3.0 0.2
5.0 4.0 0.2 0.2 0.2
0.2 0.2 0.2 3.0 0.2

Output:

MA1 MA2 MA3 MA4 MA5  MA6 MA7  MA8  MA9  MA10 MA11
4.0 0.2 0.2 0.2 0.2 2.80 2.80 2.80 2.80 2.80 2.80
3.0 4.0 0.2 3.0 0.2 2.09 2.09 2.09 2.09 2.09 2.09
0.2 0.2 0.2 0.2 0.2 0.22 0.22 0.22 0.22 0.22 0.22
0.2 4.0 1.0 0.2 2.0 1.49 1.49 1.49 1.49 1.49 1.49
0.2 0.2 0.2 3.0 0.2 0.78 0.78 0.78 0.78 0.78 0.78
5.0 4.0 0.2 0.2 0.2 1.93 1.93 1.93 1.93 1.93 1.93
0.2 0.2 0.2 3.0 0.2 0.78 0.78 0.78 0.78 0.78 0.78

Here the MA6 should be the average column values from MA1 to MA5 and MA7 should be average column values from MA1 to MA6 and so on... Can anyone help me in solving this

Upvotes: 0

Views: 209

Answers (1)

CPak
CPak

Reputation: 13591

rowMeans isn't a great example here since your values will not change after the first iteration, but try this recursive function

Your data

df <- read.table(text="MA1 MA2 MA3 MA4 MA5
4.0 0.2 0.2 0.2 0.2
3.0 4.0 0.2 3.0 0.2
0.2 0.2 0.2 0.2 0.2
0.2 4.0 1.0 0.2 2.0
0.2 0.2 0.2 3.0 0.2
5.0 4.0 0.2 0.2 0.2
0.2 0.2 0.2 3.0 0.2", header=TRUE)

Recursive function

myfun <- function(df, N, counter) {
            require(dplyr)
            if (counter > N) {
                return(df)  # return value once number of iterations is fulfilled
            } else {
                new.df <- df %>% 
                        mutate(new = rowMeans(.)) %>%  # modify data frame
                        rename_at(vars("new"), funs(paste0("MA", ncol(df)+1)))  # rename new column
                myfun(new.df, N, counter+1)  # recursive, calls function again but with modified data frame
            }
         }

myfun(df, N=5, counter=1)

  # MA1 MA2 MA3 MA4 MA5  MA6  MA7  MA8  MA9 MA10
# 1 4.0 0.2 0.2 0.2 0.2 0.96 0.96 0.96 0.96 0.96
# 2 3.0 4.0 0.2 3.0 0.2 2.08 2.08 2.08 2.08 2.08
# 3 0.2 0.2 0.2 0.2 0.2 0.20 0.20 0.20 0.20 0.20
# 4 0.2 4.0 1.0 0.2 2.0 1.48 1.48 1.48 1.48 1.48
# 5 0.2 0.2 0.2 3.0 0.2 0.76 0.76 0.76 0.76 0.76
# 6 5.0 4.0 0.2 0.2 0.2 1.92 1.92 1.92 1.92 1.92
# 7 0.2 0.2 0.2 3.0 0.2 0.76 0.76 0.76 0.76 0.76

Upvotes: 1

Related Questions