英文:
Mutate new columns and intercalate them with old ones
问题
以下是您要翻译的内容:
"我想使用 across
创建新列,并使这些新列与旧列交错。在示例中,我手动重新排列列以显示所需的输出。但我希望能够自动执行此操作,就像我在 mutate
中尝试的方式一样,显然这种方式不起作用。
library(dplyr)
df <- tibble(a = 1:2, x_b = 1:2, x_c = 1:2)
df |>
mutate(across(starts_with("x_"),
~ .x * 2,
.names = "{sub('x_', 'y_', .col)}"),
.after = c(x_b, x_c)) |>
relocate(y_b, .after = x_b) |>
relocate(y_c, .after = x_c)
#> # A tibble: 2 × 5
#> a x_b y_b x_c y_c
#> <int> <int> <dbl> <int> <dbl>
#> 1 1 1 2 1 2
#> 2 2 2 4 2 4
<sup>创建于2023年5月18日,使用 reprex v2.0.2</sup>"
英文:
I want to create new columns using across
and that new columns being intercalated with the old ones. In the example I manually relocate the columns to show the desired output. But I would like to do this automatically, like my try inside mutate
, which obviously does not work.
library(dplyr)
df <- tibble(a = 1:2, x_b = 1:2, x_c = 1:2)
df |>
mutate(across(starts_with("x_"),
~ .x * 2,
.names = "{sub('x_', 'y_', .col)}"),
.after = c(x_b, x_c)) |>
relocate(y_b, .after = x_b) |>
relocate(y_c, .after = x_c)
#> # A tibble: 2 × 5
#> a x_b y_b x_c y_c
#> <int> <int> <dbl> <int> <dbl>
#> 1 1 1 2 1 2
#> 2 2 2 4 2 4
<sup>Created on 2023-05-18 with reprex v2.0.2</sup>
答案1
得分: 5
We could create a tibble/data.frame, use .unpack
option and rename the columns
library(dplyr)
library(stringr)
df %>%
mutate(across(starts_with("x_"),
~ data.frame(x = .x, y = .x * 2), .unpack = TRUE),
.keep = 'unused') %>%
rename_with(~ str_replace(.x, "x_(.)_(.)", "\_\"))
-output
# A tibble: 2 × 5
a x_b y_b x_c y_c
<int> <int> <dbl> <int> <dbl>
1 1 1 2 1 2
2 2 2 4 2 4
英文:
We could create a tibble/data.frame, use .unpack
option and rename the columns
library(dplyr)
library(stringr)
df %>%
mutate(across(starts_with("x_"),
~ data.frame(x = .x, y = .x * 2), .unpack = TRUE),
.keep = 'unused') %>%
rename_with(~ str_replace(.x, "x_(.)_(.)", "\_\"))
-output
# A tibble: 2 × 5
a x_b y_b x_c y_c
<int> <int> <dbl> <int> <dbl>
1 1 1 2 1 2
2 2 2 4 2 4
</details>
# 答案2
**得分**: 3
A dirty workaround that I‘m using regularly:
library(tidyverse)
prefix <- c('x_', 'y_')
suffix <- c('b', 'c')
col_order <- paste0(prefix, rep(suffix, each = length(prefix)))
df %>%
select(a, all_of(col_order))
# A tibble: 2 x 5
a x_b y_b x_c y_c
<int> <int> <dbl> <int> <dbl>
1 1 1 2 1 2
2 2 2 4 2 4
<details>
<summary>英文:</summary>
A dirty workaround that I‘m using regularly:
library(tidyverse)
prefix <- c('x_', 'y_')
suffix <- c('b', 'c')
col_order <- paste0(prefix, rep(suffix, each = length(prefix)))
df %>%
select(a, all_of(col_order))
# A tibble: 2 x 5
a x_b y_b x_c y_c
<int> <int> <dbl> <int> <dbl>
1 1 1 2 1 2
2 2 2 4 2 4
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论