使用匿名函数 return 原始变量和修改后的变量

Using Anonymous Functions to return both original and modified variables

提前致歉,我正在为如何表述这个问题而苦苦挣扎,我希望我的重复表达式能够充分解释。

我正在尝试结合使用 的 mutate_ 和匿名函数对变量应用转换,目标是 return 原始变量及其转换后的对应部分到数据框。我正在努力研究如何将输出重命名为 returns 函数,同时保持原样。到目前为止,它只是 return 原始版本的修改副本。

到目前为止,我的代码采用原始输入,return将它们的转换版本发送到 current_output 对象中的数据。我尝试使用嵌套在 return() 中的 assign() 来允许更灵活的命名,并像在 desired_output 对象中一样 return 一个新变量,但没有这样的运气。

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))

我们可以使用 across 及其 .names 参数:

library(dplyr)
data %>% 
  mutate(across(c(X1, X1a), ~ .x* X2, .names = "{.col}_X2_Product"))
  X1 X1a X2 X1_X2_Product X1a_X2_Product
1  2   3  3             6              9
2  2   3  3             6              9
3  2   3  3             6              9
4  2   3  3             6              9

此答案并未遵守问题要求的所有限制条件,但出于喜剧效果:

library(base)  # I know...

data$X1_X2_Product  <- data$X1  * data$X2
data$X1a_X2_Product <- data$X1a * data$X2