skip to Main Content

I am trying to remove the first | in my data. When I run the following:

yy <- y %>% 
  mutate_all(funs(sub("|", "", .)))

Nothing happens.

I have other occurrences of | in the other columns so I do not want to remove all of them. I was able to remove the last occurrence of the | using the following mutate_all(funs(gsub("(.*)\|(.*)", "\1\2", .))) – Now I want to do the same but for the first occurrence.

Data:

y <- structure(list(grp = c("2902", "9738", "9143", "3990", "10488", 
"9581", "10905", "9859", "8787", "8626"), HD = c("| CarrolsRestr 4Q EPS 16c Vs EPS 22c       ", 
"| Press Release: Fitch Affirms Aeroports de Paris SA at 'A+'; Outlook Stable    ", 
"| MSC Reports Fiscal 2017 First Quarter Results    ", "| Goodrich Announces Third Quarter 2009 Net Income per Diluted Share of $1.14, Adjusts Outlook for Full Year 2009, Provides Outlook for 2010    ", 
"| *Vera Bradley 1Q Loss/Shr 4c >VRA    ", "| *Fitch Affirms One Re's IFS at 'BBB-'; Outlook Stable    ", 
"| Johnson Controls 2014 first quarter earnings increase 31 percent on higher revenues and improved profitability; affirms guidance for fiscal 2014    ", 
"| eBay Inc. Reports Third Quarter 2017 Results    ", "| S&P Rating Shift a Sober Reminder for Australia -- Market Talk    ", 
"| Jeff Immelt: GE 'Underowned' by Big Investors    "), WC = c("| 191 words    ", 
"| 2,493 words    ", "| 2,068 words    ", "| 6,275 words    ", 
"| 3,912 words    ", "| 1,907 words    ", "| 2,452 words    ", 
"| 5,227 words    ", "| 1,594 words    ", "| 920 words    ")), class = "data.frame", row.names = c(NA, 
-10L))

3

Answers


  1. This works for me:

    y$HD <- sub("|", "", y$HD, fixed = TRUE)
    y$WC <- sub("|", "", y$WC, fixed = TRUE)
    
    Login or Signup to reply.
  2. This code works for me on the sample data y you provided

    y %>% 
      mutate_all(funs(sub("\|", "", .)))
    

    Basically you need to escape the character |

    Login or Signup to reply.
  3. We can also do with str_remove

    library(dplyr)
    library(stringr)
    y %>%
      mutate_all(str_remove, pattern = fixed("|"))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search