Home > OS >  Rename columns that start with prefix and delete periods using gsub?
Rename columns that start with prefix and delete periods using gsub?

Time:03-14

I have a dataframe where I want to rename only column names that start with "Q" to be lowercase and remove periods. I thought gsub with regex would be the appropriate but I'm inexperienced with it. This is what I have managed to do so far but I get an error message right now:

Error: Can't convert a character vector to function

df <- data.frame(A.1 = character(), 
                 Q1.1 = character(), 
                 Q1.2 = character())
df <- df %>% rename_with(
  gsub('Q\\d', 'q.', names(df))
)

A.1 would remain as is, but Q1.1 would become q11.

CodePudding user response:

rename_with can take a select statement, so we can use starts_with to apply the function just to those columns that start with Q.

library(dplyr)

df %>%
  rename_with(.fn = ~ tolower(gsub(".", "", .x, fixed = TRUE)), .col = starts_with("Q"))

#[1] A.1 q11 q12
#<0 rows> (or 0-length row.names)

Or with stringr:

library(stringr)

df %>%
  rename_with(.fn = ~ str_to_lower(str_replace_all(.x, "\\.", "")), .col = starts_with("Q"))

CodePudding user response:

Here’s one Base R option using regex group captures:

df <- data.frame(
    A.1 = character(),
    Q1.1 = character(),
    Q1.2 = character())

df |> setNames(gsub("^Q(.*)\\.(.*)", "q\\1\\2", names(df)))

    ## [1] A.1 q11 q12
    ## <0 rows> (or 0-length row.names)
  • Related