Home > Software engineering >  multiply all values in all columns by the number of days that correspond to the month in date?
multiply all values in all columns by the number of days that correspond to the month in date?

Time:04-13

An example of my data is here

    dput(s2[2,])
 structure(list(date = structure(4049, class = "Date"), `A` = 7, 
`At` = 0.0001780556), row.names = 2L, class = "data.frame")

How can I multiply all values in all columns by the number of days that correspond to the month in date and multiply by 10

CodePudding user response:

With days_in_month function from lubridate we could extract the days of the present month, in this case 28 and then use across for each column except date and multiple by days_in_month(date) and by 10:

library(lubridate)
library(dplyr)
df %>% 
  mutate(across(-date, ~days_in_month(date)*.*10))

        date    A         At
2 1981-02-01 1960 0.04985557

In case you want to keep the original values:

df %>% 
  mutate(across(-date, ~days_in_month(date)*.*10, .names = "calculated_{.col}"))
        date A           At calculated_A calculated_At
2 1981-02-01 7 0.0001780556         1960    0.04985557

Or as suggested by @mkpt_uk:

df %>% 
  mutate(across(-date, list(mult = ~days_in_month(date)*.*10)))
        date A           At A_mult    At_mult
2 1981-02-01 7 0.0001780556   1960 0.04985557
  •  Tags:  
  • r
  • Related