2

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))
user8959427
  • 2,027
  • 9
  • 20
  • You said you don't want to remove the `|` in all the columns, but you tried to use `mutate_all`. Am I missing something? – Ric S Apr 23 '20 at 14:33
  • Apologies. I don't want to remove all of the `|` - just the first one. In some other columns I have something like `| text1 | text2 | text3` - I want to have just `text1 | text2 | text3`. – user8959427 Apr 23 '20 at 14:39

3 Answers3

2

This works for me:

y$HD <- sub("|", "", y$HD, fixed = TRUE)
y$WC <- sub("|", "", y$WC, fixed = TRUE)
Matt
  • 7,255
  • 2
  • 12
  • 34
1

This code works for me on the sample data y you provided

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

Basically you need to escape the character |

Ric S
  • 9,073
  • 3
  • 25
  • 51
1

We can also do with str_remove

library(dplyr)
library(stringr)
y %>%
  mutate_all(str_remove, pattern = fixed("|"))
akrun
  • 874,273
  • 37
  • 540
  • 662