我想使用新列来创建新列across,并将新列与旧列插入。在示例中,我手动重新定位列以显示所需的输出。但我想自动执行此操作,就像我的 try inside 一样mutate,这显然不起作用。
library(dplyr)\n\ndf <- tibble(a = 1:2, x_b = 1:2, x_c = 1:2)\n\ndf |> \n mutate(across(starts_with("x_"), \n ~ .x * 2, \n .names = "{sub(\'x_\', \'y_\', .col)}"),\n .after = c(x_b, x_c)) |> \n relocate(y_b, .after = x_b) |> \n relocate(y_c, .after = x_c)\n\n#> # A tibble: 2 \xc3\x97 5\n#> a x_b y_b x_c y_c\n#> <int> <int> <dbl> <int> <dbl>\n#> 1 1 1 2 1 2\n#> 2 2 2 4 2 4\nRun Code Online (Sandbox Code Playgroud)\n创建于 2023-05-18,使用reprex v2.0.2
\n我们可以创建一个 tibble/data.frame,使用.unpack选项并重命名列
library(dplyr)\nlibrary(stringr)\ndf %>%\n mutate(across(starts_with("x_"), \n ~ data.frame(x = .x, y = .x * 2), .unpack = TRUE),\n .keep = 'unused') %>% \n rename_with(~ str_replace(.x, "x_(.)_(.)", "\\\\2_\\\\1"))\nRun Code Online (Sandbox Code Playgroud)\n-输出
\n# A tibble: 2 \xc3\x97 5\n a x_b y_b x_c y_c\n <int> <int> <dbl> <int> <dbl>\n1 1 1 2 1 2\n2 2 2 4 2 4\nRun Code Online (Sandbox Code Playgroud)\n