Search code examples
rmultiple-columnsframe

Operations on multiple columns accross many tables


I have two tables (dt1, dt2). dt2 contains the same variables names as dt1. For each variable in dt1 I would like to multiply it with its values from dt2. In the exemple below, x from dt1 will get multiplied with 4 and y with 7. How would be the fast way to do it? Thank you

  set.seed(123)
  dt1 <- data.frame(x = sample(1:10, 10, TRUE), y = sample(1:10, 10, TRUE) )
  dt1
  dt2 = data.frame (names = c("x", "y"), values = c(4, 7))
  dt2

Solution

  • purrr style

    map2_df(dt1, dt2 %>% pivot_wider(names_from = names, values_from = values), ~.y * .x)
    
    # A tibble: 10 x 2
           x     y
       <dbl> <dbl>
     1    12    35
     2    12    21
     3    40    63
     4     8    63
     5    24    63
     6    20    21
     7    16    56
     8    24    70
     9    36    49
    10    40    70