简体   繁体   中英

R gsub returns incorrect data

I am new to using R and I am having issues with using gsub to format my list properly. I am needing to make two replacements.

  • First replacement replacing everything after @ with @mydomain.com
  • Second replacement replacing all www. with an empty value.

Update

I am currently running gsub twice and corrected with my code it works. I had too many gsub instances that i didnt see.

vec <- c('john@mail.com', 'mike@mail.com', 'robbie.b@yahoo.com', 
         'zack.l.harris@aol.com', 'www.google.com', 'www.gmail.com', 
         'www.domain.com', 'www.example.com')

vec <- gsub("@.*\\.com", "@mydomain.com", vec)
vec <- gsub("www\\.", "", vec)

print(vec)

Update

But I want to run gsub as one instance replacing both at the same time if possible still.

One way I've done this, you could cascade your gsub functions together.

vec <- gsub('@[^.]*\\.[^.]*', '@mydomain.com', gsub('www\\.', '', vec))
print(vec)

Another solution is to create vectors for your old values and replacement values

re  <- c('@[^.]*\\.[^.]*', 'www\\.')
val <- c('@mydomain.com',  '')

recurse <- function(pattern, repl, x) {
    for (i in 1:length(pattern))
       x <- gsub(pattern[i], repl[i], x)
       x
}

vec <- c('john@mail.com', 'mike@mail.com', 'robbie.b@yahoo.com', 
         'zack.l.harris@aol.com', 'www.google.com', 'www.gmail.com', 
         'www.domain.com', 'www.example.com')

print(recurse(re, val, vec))

Output

"john@mydomain.com"          "mike@mydomain.com"         
"robbie.b@mydomain.com"      "zack.l.harris@mydomain.com"
"google.com"                 "gmail.com"                 
"domain.com"                 "example.com"     

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