rename multiple columns with a vector

Instead of starts_with, we could use matches as starts_with expects a single input, while matches can have multiple values if we create a single string concatened with | (OR)

library(dplyr)
library(stringr)
df %>%
   rename_at(vars(matches(str_c(ensembl, collapse="|"))),
          ~genes) 

-output

# A tibble: 1 x 3
#  sample    ACTB GAPDH
#  <chr>    <dbl> <dbl>
1 sample_A    12    20

Or another option is to remove the . followed by the characters in the column names that starts with ‘Ensembl’ and use a named vector in rename

df %>% 
    rename_at(vars(starts_with("Ensembl")), ~ str_remove(., "\\..*")) %>%
    rename(!!! setNames(ensembl, genes))
# A tibble: 1 x 3
#  sample    ACTB GAPDH
#  <chr>    <dbl> <dbl>
#1 sample_A    12    20

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top