Overwriting Multiple String Variables with Loop or Apply

Viewed 83

I am trying to use a loop or apply to more than one variable in a data frame to remove some accents without creating new variables. Here is an example data frame with two grandfathers, their sons' names, and how many grandchildren they have:

df <- data.frame(
        grandfather = c("Ramón", "Chris"), 
        son = c("José", "Mike"),
        grandchildren = c(3,4))

Now I create a function to remove the accents in José and Ramón:

remove.accents <- function(s) {
  old1 <- "óé"
  new1 <- "oe"
  s1 <- chartr(old1, new1, s)
}

Clearly, I could do this by just overwriting each variable one at a time:

df$grandfather = remove.accents(df$grandfather)
df$son = remove.accents(df$son)

How could I do this with a loop or apply function while still keeping the same data frame--instead of writing things one at a time? Thanks in advance?

1 Answers

You can use across:

library(dplyr)
df %>% mutate(across(where(is.character),remove.accents))

  grandfather  son grandchildren
1       Ramon Jose             3
2       Chris Mike             4
Related