Divide the line above to the line below

I have the following input frame:

df1 <- data.frame(row.names=c("AA","BB","CC","DD","EE"), A=c(0.90,0.75,0.65,0.55,0.45), B=c(0.80,0.75,0.60,0.60,0.45))

Row  A   B
AA   0.90 0.80
BB   0.75 0.75
CC   0.65 0.60
DD   0.55 0.60
EE   0.45 0.45

Is there a way to divide the values ​​in row AA by the value in row BB (0.90 / 0.75 = 1.200). Then I want to split this new value in line BB by the value in line CC (1.2 / 0.65 = 1.846), etc. To create the following output frame:

Row  A     B
A   0.900 1.067
B   1.200 1.067
C   1.846 1.778 
D   3.357 2.963
E   7.459 6.584

I really scratch my head with this, so any help is greatly appreciated.

Thanks guys!

+4
source share
2 answers

You can use a simple loop foror cumprod:

df2 <- df1
for (i in 2:nrow(df2)) {
  df2[i, ] <- df2[i-1,]/df2[i,]
}

Depending on the number of columns, the approach cumprodshould be much faster:

df3 <- df1
df3$A <- cumprod(c(df3[1, "A"], 1/df3[-1, "A"]))
df3$B <- cumprod(c(df3[1, "B"], 1/df3[-1, "B"]))

all.equal(df2, df3)
# TRUE
+3
source

Reduce , accumulate = TRUE

as.data.frame(lapply(df1, Reduce, f = `/`, accumulate = TRUE))

( , , , , .)

+2

Source: https://habr.com/ru/post/1529673/


All Articles