Reputation: 3447
Consider that we have the below data and would like to derive variables z1,z2,z3 from x1y1, x2y2 and x3*y3.
could you please help me how i can achieve this in R
x1 <- c(1,2,3,4,5,6)
x2 <- c(2,3,4,5,6,7)
x3 <- c(3,4,5,6,7,8)
x4 <- c('A','B','C','D','E','F')
y1 <- c(1,2,3,4,5,6)
y2 <- c(2,3,4,5,6,7)
y3 <- c(3,4,5,6,7,8)
testa <- data.frame(x1,x2,x3,x4,y1,y2,y3)
Upvotes: 0
Views: 35
Reputation: 886948
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
Upvotes: 1
Reputation:
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
Upvotes: 1