derive multiple columns from multiple columns in r
Assuming the integrity of your structure and naming conventions, you can select the x
and y
variables, multiple them together as a group, and then assign back to z
.
var_i <- 1:3
testa[paste0("z", var_i)] <- testa[paste0("x", var_i)] * testa[paste0("y", var_i)]
x1 x2 x3 x4 y1 y2 y3 z1 z2 z3
1 1 2 3 A 1 2 3 1 4 9
2 2 3 4 B 2 3 4 4 9 16
3 3 4 5 C 3 4 5 9 16 25
4 4 5 6 D 4 5 6 16 25 36
5 5 6 7 E 5 6 7 25 36 49
6 6 7 8 F 6 7 8 36 49 64
If we want to do this automatically, a tidyverse
option is
library(dplyr)
library(stringr)
testa <- testa %>%
mutate(across(x1:x3, ~ .x * get(str_replace(cur_column(), "x",
"y")), .names = "{str_replace(.col, 'x', 'z')}"))
-output
testa
x1 x2 x3 x4 y1 y2 y3 z1 z2 z3
1 1 2 3 A 1 2 3 1 4 9
2 2 3 4 B 2 3 4 4 9 16
3 3 4 5 C 3 4 5 9 16 25
4 4 5 6 D 4 5 6 16 25 36
5 5 6 7 E 5 6 7 25 36 49
6 6 7 8 F 6 7 8 36 49 64