Home > database >  Replace specific character from all columns of a dataframe
Replace specific character from all columns of a dataframe

Time:10-23

Having a dataframe like this:

df <- data.frame(id = c(1,2), date1 = c("Nov 2016 <U 2192> Current", "Nov 2016 <U 2192> Current"), date2 = c("Nov 2016 <U 2192> Current", "Nov 2016 <U 2192> Current"))

Is there any command to replace this character in the whole dataframe?

Example:

df <- gsub(' <U 2192> ', '-', df)

CodePudding user response:

Placing it here also as an answer:

library(dplyr)

df %>% mutate(across(everything(), ~ gsub(' <U 2192> ', '-', ., fixed = TRUE)))

Output

  id            date1            date2
1  1 Nov 2016-Current Nov 2016-Current
2  2 Nov 2016-Current Nov 2016-Current

CodePudding user response:

A base R solution with sapply:

df <- sapply(df, function(x) gsub(" <U\\ 2192>", " -", x))

Note that must be escaped unless you use the fixed = TRUE argument

df
     id  date1                date2               
[1,] "1" "Nov 2016 - Current" "Nov 2016 - Current"
[2,] "2" "Nov 2016 - Current" "Nov 2016 - Current"
  • Related