简体   繁体   中英

Removing the special symbols in data.frame column values

I have two data frame each with a column Name

df1 :

name  
@one2  
!iftwo  
there_2_go  
come&go

df1 = structure(list(name = c("@one2", "!iftwo", "there_2_go", "come&go")),.Names = c("name"), row.names = c(NA, -4L), class = "data.frame")

df2 :

name  
One2  
IfTwo#  
there-2-go  
come.go



df2 = structure(list(name = c("One2", "IfTwo#", "there-2-go", "come.go")),.Names = c("name"), row.names = c(NA, -4L), class = "data.frame")

Now to compare the two data frames for inequality is cumbersome because of special symbols using %in% . To remove the special symbols using stringR can be useful. But how exactly we can use stringR functions with %in% and display the mismatch between them

have already done the mutate() to convert all in lowercases toLower() as follows

df1<-mutate(df1,name=tolower(df1$name))
df2<-mutate(df2,name=tolower(df2$name))

Current output of comparison:

df2[!(df2 %in% df1),]
[1] "one2"       "iftwo#"     "there-2-go" "come.go" 

Expected output as essentially the contents are same but with special symbols:

 df2[!(df2 %in% df1),]
 character(0)

Question : How do we ignore the symbols in the contents of the Frame

Here it is in a function,

f1 <- function(df1, df2){
  i1 <- tolower(gsub('[[:punct:]]', '', df1$name))
  i2 <- tolower(gsub('[[:punct:]]', '', df2$name))
  d1 <- sapply(i1, function(i) grepl(paste(i2, collapse = '|'), i))
  return(!d1)
}

f1(df, df2)
#    one2    iftwo there2go   comego 
#   FALSE    FALSE    FALSE    FALSE 

#or use it for indexing,

df2[f1(df, df2),]
#character(0)

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