Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutate new columns and intercalate them with old ones

Tags:

r

dplyr

tidyverse

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

Created on 2023-05-18 with reprex v2.0.2

like image 871
Josep Pueyo Avatar asked Oct 15 '25 10:10

Josep Pueyo


1 Answers

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_(.)_(.)", "\\2_\\1"))

-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
like image 111
akrun Avatar answered Oct 19 '25 09:10

akrun