cephalopod
cephalopod

Reputation: 1906

how to multiply multiple df columns

I have a df with a number of columns. I want to multiply each of the column using a fixed constant. I am looking for the best possible strategy to achieve this using purrr (I am still trying to get my head around lamp etc etc)

library(tidyverse)
library(lubridate)

df1 <- data.frame(
               date = ymd(c("2019-02-01", "2019-02-02", "2019-02-03", "2019-02-04",
                        "2019-02-05")),
                  x = c(1, 2, 3, 4, 5),
                  y = c(2, 3, 4, 5, 6),
                  z = c(3, 4, 5, 6, 7)
       ) 

The constants to multiply each of the column is as follows:

c(10, 20, 30)

This is the output I expect:

data.frame(
        date = ymd(c("2019-02-01", "2019-02-02", "2019-02-03", "2019-02-04",
                 "2019-02-05")),
           x = c(10, 20, 30, 40, 50),
           y = c(40, 60, 80, 100, 120),
           z = c(90, 120, 150, 180, 210)
)

Upvotes: 2

Views: 62

Answers (1)

www
www

Reputation: 39154

We can use map2 from purrr (part of the tidyverse) to achieve this.

df1[2:4] <- map2(df1[2:4], c(10, 20, 30), ~.x * .y)
df1        
#         date  x   y   z
# 1 2019-02-01 10  40  90
# 2 2019-02-02 20  60 120
# 3 2019-02-03 30  80 150
# 4 2019-02-04 40 100 180
# 5 2019-02-05 50 120 210

The base R equivalent is mapply.

df1[2:4] <- mapply(FUN = function(x, y) x * y, df1[2:4], c(10, 20, 30), SIMPLIFY = FALSE)

Upvotes: 4

Related Questions