Search code examples
rgsubmutate

How to capitalize the first letter in a list of columns?


Here is my dataframe:

col1 <- c("hello my name is", "Nice to meet you", "how are you")
col2 <- c("dog", "Cats", "Frogs are cool")
col3 <- c("Pause", "breathe in and out", "what are you talking about")
df <- data.frame(col1, col2, col3)

I want to apply gsub on the following variables in my df:

vars <- c("col1", "col2")

I want to use gsub to capitalize the first letter of every cell:

df <- df %>%
  as_tibble() %>%
  mutate(across(vars), gsub, pattern = "^(\\w)(\\w+)", replacement = "\\U\\1\\L\\2", perl = TRUE)

But I'm getting the following error:

Error in `mutate_cols()`:
! Problem with `mutate()` input `..2`.
ℹ `..2 = gsub`.
x `..2` must be a vector, not a function.
Run `rlang::last_error()` to see where the error occurred.

Any guidance would be appreciated!


Solution

  • Fix your parentheses:

    df %>%
      as_tibble() %>%
      mutate(across(any_of(vars), gsub, pattern = "^(\\w)(\\w+)", replacement = "\\U\\1\\L\\2"))
    

    Although I don‘t think your regex is doing what you want:

    # A tibble: 3 x 3
      col1               col2             col3                      
      <chr>              <chr>            <chr>                     
    1 UhLello my name is UdLog            Pause                     
    2 UNLice to meet you UCLats           breathe in and out        
    3 UhLow are you      UFLrogs are cool what are you talking about