简体   繁体   中英

how to convert special characters as blank in data frame

i Have a df which contains special character that starts with "-" as shown in below df

A = c("A","A","A","A","A")
B =c("---","21","31","423","e")
C = c("0","0","----","p","1.75")
D = c("10","-----","d","-","1.3")
E = c("0","---","N","1.5","1.75")
df =  data.frame(A,B,C,D,E)

I am getting error while trying to make values as blanks values which starts with "-" with below code,

df1 = str_replace_all(df, grepl("-",df), " ")

Thanks in advance

We can do this with mutate_all as grepl works on vector/matrix and not on data.frame

library(dplyr)
df %>%
    mutate_all(funs(replace(., grepl('-', .), '')))
#  A   B    C   D    E
#1 A        0  10    0
#2 A  21    0         
#3 A  31        d    N
#4 A 423    p      1.5
#5 A   e 1.75 1.3 1.75

Or using str_replace

library(stringr)
df %>%
     mutate_all(funs(str_replace(., "^-+$", "")))

With base R , we can use lapply

df[] <- lapply(df, function(x) replace(x, grepl('-', x), ''))

It is better to create character columns instead of factor . Using stringsAsFactors = FALSE in data.frame does that

data

df <- data.frame(A,B,C,D,E, stringsAsFactors = FALSE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM