Replace special character in data frame

Viewed 1267

I have a dataframe which contains in different cells a special character which I know which is. An example of the structure:

df = data.frame(col_1 = c("21 myspec^ch2 12",NA), 
                col_2 = c("1 myspec^ch2 4","4 myspec^ch2 212"))

The character is this myspec^ch2 and I would like to replace with -. An example of expected output:

df = data.frame(col_1 = c("21-12",NA), 
                col_2 = c("1-4","4-212"))

I tried this but it is not working:

df [ df == " myspec^ch2 " ] <- "-"
2 Answers

To get gsub work on whole dataframe use apply:

apply(df, 2, function(x) gsub(" myspec\\^ch2 ", "-", x))

You really want to do a regex-style substitution here. However, in regex, ^ is seen as the beginning of the line (rather than a literal caret). So you can do something like this (using the stringr package):

library(dplyr)
library(stringr)

fixed_df  <- df %>%
    mutate_all(funs(str_replace_all( . , " myspec\\^ch2 ", "-"))

Note the double backslashes in front of the caret--that escapes the caret and tells R to interpret it literally, rather than as the beginning of the line.

Related