Search code examples
rdataframetidyversemultiplicationscalar

How to multiply a scalar value across multiple columns in R data.frame?


I have the following data.frame and i would like to multiply only the numeric columns by a scalar value.

library(tidyverse)
library(lubridate)

set.seed(123)

D1 <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2001-01-10"), by="day"),
                 A1= runif(10,1,5),
                 B2 = runif(10,3,6),
                 C9 = runif(10,2,5))

I tried the following but it eliminate the Date column

D <- D1 %>% 
    select(,c(2:4))*1000

Also this one remove the Date column as well.

D <- D1 %>% 
  select_if(is.numeric)*1000

Are there any option that would keep the Date column and does the multiplication ?


Solution

  • I hope this is what you are looking for:

    library(dplyr)
    
    D1 %>%
      mutate(across(where(is.numeric), ~ .x * 1000))
    
             Date       A1       B2       C9
    1  2001-01-01 3915.198 5360.962 3216.361
    2  2001-01-02 1984.007 3316.846 4443.792
    3  2001-01-03 2888.303 5870.227 4606.728
    4  2001-01-04 1955.763 5771.595 3273.241
    5  2001-01-05 1533.243 3205.139 3254.499
    6  2001-01-06 3129.899 4899.974 3063.600
    7  2001-01-07 1873.876 5107.482 4142.117
    8  2001-01-08 3807.380 5759.612 2448.172
    9  2001-01-09 1396.257 5009.001 4648.551
    10 2001-01-10 1280.629 5441.055 4858.487