Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading