# Multiply columns across

Hello,

I have columns a,b,c,x,y,z and would like to create new columns by multiplying ax, by and c*z

``````
library(tidyverse)

(mytable <- data.frame(
a=1:2,
b=2:3,
c=3:4,
x=5:6,
y=7:8,
z=9:10
))
``````

thank you

Try this:

``````mytable |>
as_tibble() |>
mutate(ax = a*x,
by = b*y,
cz = c*z)
``````
1 Like

thanks....how about if i want to do it for very many column pairs i.e 30, is there an easier way to handle it

``````library(tidyverse)
library(rlang)
(mytable <- data.frame(
a=1:2,
b=2:3,
c=3:4,
x=5:6,
y=7:8,
z=9:10
))
ncm <- ncol(mytable)
(first_cols <- seq_len(ncm/2))
(second_cols <- setdiff(seq_len(ncm),first_cols))
first_half_names <- names(mytable)[first_cols]
second_half_names <- names(mytable)[second_cols]

(step_1 <- map2(first_half_names,
second_half_names,
\(x,y) paste0(x,"*",y) ))
(step_2 <- map2(first_half_names,
second_half_names,
\(x,y) paste0(x,y) ))

(step_3 <- rlang::parse_exprs(paste0(step_1,collapse=";")))
names(step_3) <- step_2
step_3

mutate(mytable,
!!!(step_3))``````

This topic was automatically closed 21 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.