Multiply many columns

Hello,

I have 4 variables (say t1, t2, t3, t4) and another 4 variables (say var1, var2, var3, var4) - naming convention is a little longer and not so well-defined (happy to rename if that makes it more streamlined).

I need to multiple each of the first bunch of variables with the second - i.e. 16 variables like t1v1, t1v2....t4*v4. I'm a beginner to loops/functions and quite confused.. any help would be great!

The data is in the format: (there are more columns in the dataframe too, if that is relevant)

df <- data.frame(name = c("Tom", "Henry", "Linda", "Olivia"),
                t1= c(0, 1, 0, 1),
                t2= c(0, 1,1, 0),
                t3= c(0, 0, 0, 1),
                t4= c(1, 1, 0, 1),
                v1= c(NA, 3.6, 3.5, NA),
                v2 = c(NA, 3.3, 3.4, 4.9),
                v3= c(7, 10, NA, 3),
                v4 = c(44, 37, NA, 29))

Thank you!

Hello,

It would be helpful if you could give us a representative example. You can find a guide here.

Thank you, have edited!


library(glue)
library(purrr)
library(dplyr)

tnums <- 1:4

bind_cols(
  df,
  map_dfc(
    tnums,
    ~ df[[glue("t{.}")]] * df[[glue("v{.}")]]
  ) %>%
    set_names(map_chr(tnums, ~ glue("t_times_v_{.}")))
)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.