我有一些数据,我想进行一系列的计算。
数据如下所示:
col1 col2 col3 col1_Q col2_Q col3_Q
1 -0.5296808 -0.54167256 2.6416685 -0.5366250 1.19984571 0.19871640
2 1.9371126 -0.07313745 1.4779668 0.1037590 1.48971454 2.41751947
3 1.8017264 -0.19397778 -0.1828478 1.1360315 -1.11973525 0.54872807
4 0.7959393 0.54337963 -0.9444652 0.9525416 -0.82435175 0.85590371
5 -0.7666921 -1.22480510 -1.2418267 0.1530689 1.05904890 -0.43619405
6 -0.1647869 1.58908958 0.8987575 1.0575849 1.19266752 2.49259874
7 0.6760979 0.86774719 0.9480558 1.9573319 -0.00333835 0.09715238
8 -0.7226570 -0.78715755 -0.0221244 0.6955029 0.91267991 1.97211329
9 -0.2916513 -2.04597956 -1.0463820 -0.2448320 -0.80166229 -1.39243275
10 -0.5208863 1.13951660 -0.1240798 -0.9814012 -1.41960227 -0.63468344
在这部分代码中
data %>%
mutate(across(c(all_of(myColumnsToMutate)), ~lag(.x, 1), .names = "{.col}_L1")) %>%
mutate(across(c(all_of(myColumnsToMutate)), ~lag(.x, 2), .names = "{.col}_L2")) %>%
mutate(across(c(all_of(myColumnsToMutate)), ~lag(.x, 3), .names = "{.col}_L3")) %>%
mutate(across(cols = c(myColumnsToMutate), ~ my_function(.x = myColumnsToMutate[1:3], .y = myColumnsToMutate[4:6])))
我试图创建滞后,但我也试图传递2个变量给一个函数。如何使用glue
来改变每个列对?例如col1
与col1_Q
以及col2
与col2_Q
。
代码和数据
library(tidyverse)
data = data.frame(
col1 = rnorm(1:10),
col2 = rnorm(1:10),
col3 = rnorm(1:10),
col1_Q = rnorm(1:10),
col2_Q = rnorm(1:10),
col3_Q = rnorm(1:10)
)
myColumnsToMutate = colnames(data)
data %>%
mutate(across(c(all_of(myColumnsToMutate)), ~lag(.x, 1), .names = "{.col}_L1")) %>%
mutate(across(c(all_of(myColumnsToMutate)), ~lag(.x, 2), .names = "{.col}_L2")) %>%
mutate(across(c(all_of(myColumnsToMutate)), ~lag(.x, 3), .names = "{.col}_L3")) %>%
mutate(across(cols = c(myColumnsToMutate), ~ my_function(.x = myColumnsToMutate[1:3], .y = myColumnsToMutate[4:6])))
my_function = function(var_1, var_2){
var_1 * var_2
}
1条答案
按热度按时间6uxekuva1#
使用
dplyr::cur_column()
和get
,您可以执行以下操作: