Apologies in advance, I'm struggling with how to phrase this question and I hope my repex is sufficiently explanatory.
I'm trying to use a combination of tidyverse's mutate_ and anonymous functions to apply a transformation to a variable with the goal of returning the original variable and its transformed counter part to the data frame. I'm struggling on how to rename the output the function returns, while keeping the original. So far it only returns the modified copy of the original.
So far, my code takes the original inputs, and returns their transformed versions to the data such as in the current_output object. I tried to use assign() nested in return() to allow for more flexible naming and to return a new variable all together like in the desired_output object but no such luck.
library(tidyverse)
data <- data.frame(X1 = c(2, 2, 2, 2),
X1a = c(3, 3, 3, 3),
X2 = c(3, 3, 3, 3))
data%>%
mutate_at(vars(X1,
X1a),
function(x){
X2 = get("X2", parent.frame())
X1a = x * X2
return(assign(paste(x, "X2", "_Product", sep = "_"), X1a))
}) -> data2
desired_output <- data.frame(X1 = c(2, 2, 2, 2),
X1a = c(3, ,3 , 3),
X2 = c(3, 3, 3, 3),
X1_X2_Product = c(6, 6, 6, 6),
X1a_X2_Product = c(9, 9, 9, 9))
current_output <- data.frame(X1 = c(6, 6, 6, 6),
X1a = c(9, 9, 9, 9),
X2 = c(3, 3, 3, 3))
data %>% mutate(across(starts_with("X1"), ~ .x * X2, .names = "{.col}_X2_Product")). Don't usemutate_at()- it's been retired in favor ofacross().data %>% mutate_at(vars(X1, X1a), list(X2_product = ~.x * X2))ordata %>% mutate(across(c(X1, X1a), list(X2_product = ~.x * X2)))