I would like to duplicate a certain subset of columns whose names are suffixed by numbers. To the nummerical suffixes of new columns should be added a certain offset (in the following example it's 12).
Unfortunately, my code isn't working at all and on top, it seems unreasonably complicated.
library(tidyverse)
df <- data.frame(
v_1 = c('Aira', 'Ben', 'Cat'),
v_2 = c(23, 32, 27),
v_3 = c(90, 98, 95)
)
# Duplicate columns using mutate across
df2 <- df %>% mutate(
across(
.cols = starts_with('v'),
.names = paste("x", toString(strtoi(strsplit({.col}, '_')[[1]][2]) 12, sep="_"))
)
)
CodePudding user response:
this works for the given example, using dplyr::across()
:
df %>%
dplyr::mutate(across(v_1:v_3,
.fns = ~ .x,
.names = "x_{as.numeric(stringr::str_sub(.col, 3, 3)) 12}"))
v_1 v_2 v_3 x_13 x_14 x_15
1 Aira 23 90 Aira 23 90
2 Ben 32 98 Ben 32 98
3 Cat 27 95 Cat 27 95
CodePudding user response:
bind_cols(
df,
df %>% rename_with(
.cols=starts_with("v_"),
.fn=\(x) paste0("v_",as.numeric(stringr::str_extract_all(x,"\\d")) 12)
)
)
You can also use mutate(across())
as you were planning, like this:
df %>% mutate(across(
.cols=starts_with("v_"),
.names="{paste0('v_',as.numeric(stringr::str_extract(col,'\\\\d')) 12)}"
))