Home > Blockchain >  How to iterate growth based on daily growth rate for multiple columns using a for loop
How to iterate growth based on daily growth rate for multiple columns using a for loop

Time:06-24

I have a df with growth rates per species A, B, and C for about 60 days. df1 is an example.

df1 <- data.frame(Day = c('59','60' ), A= c('.1', '.6'), B= c('.2', '.5'), C=c('.3','.4'))

df1=Growthrates

I am calculating the cell count for each day based on a given initial cell count (1000). I want a df that uses the initial cell count and the corresponding daily growth rate for each species from df1 such that the calculated cell count under each column (A,B,or C) in df2 is calculated with the cell count from the previous day and the rate from "today".

Using the example above, I could start with my second df (df2) on day 58 (rather than 59 like in df1) and calculate each value thereafter.

df2 <- data.frame(Day = c('58','59','60' ), A= c('1000', '1100', '1760'), B= c('1000','1200', '18000'), C=c('1000','1300','1820'))

df2=calculated cell counts (with initial input as 1000). The remaining provided values are what would be expected if the calculation is successful.

The simple equation is as follows for any particular species:

Day59 Cell count= Cell count(day 58)*( 1 growth rate (day 59))

After the initial cell count, it will need to use the newly generated value as input for the next calculation

Cell count (day 60)= Cell count (day 59)*( 1 growth rate (day 60))

I am having trouble converting this to a for loop where. Any help is much appreciated.

Thank you in advance.

CodePudding user response:

library(dplyr)
df2 <- df1 %>% mutate(across(-Day, ~1000*cumprod(as.numeric(.x) 1))) %>%
  add_row(Day = '58', A = 1000, B = 1000, C = 1000, .before = 1)

  Day    A    B    C
1  58 1000 1000 1000
2  59 1100 1200 1300
3  60 1760 1800 1820

EDIT: I think this is better, since it actually uses the day 58 values, in case those vary:

data.frame(Day = '58', A = 1000, B = 2000, C = 5000) %>% # or other values
  bind_rows(df1 %>% mutate(across(-Day, ~(as.numeric(.x) 1)))) %>%
  mutate(across(-Day, ~cumprod(.x)))

  Day    A    B    C
1  58 1000 2000 5000
2  59 1100 2400 6500
3  60 1760 3600 9100
  • Related