Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace special character in data frame

Tags:

r

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 " ] <- "-"
like image 322
PitterJe Avatar asked Jul 19 '26 18:07

PitterJe


2 Answers

To get gsub work on whole dataframe use apply:

apply(df, 2, function(x) gsub(" myspec\\^ch2 ", "-", x))
like image 134
pogibas Avatar answered Jul 21 '26 07:07

pogibas


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.

like image 32
crazybilly Avatar answered Jul 21 '26 09:07

crazybilly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!