Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add space after – in a value when there is no space after it

Based on the data below how can I add a space after the special character - only when there is no space after it which in this case is for fiscal year 2012 -2013? I know I have to use gsub but, it always confuses me so some explanation would be appreciated.

Sample data and code:

id = c (1,2,3,4,5,6,7,8,9,10)
FiscalYear = c("2012 -2013", "2012 -2013", "2012 -2013", "2012 -2013", "2012 -2013",
               "2014 - 2015", "2014 - 2015", "2014 - 2015", "2014 - 2015", "2014 - 2015")
# Sample
df = data.frame(id, FiscalYear)

# Updated Sample
df_new = df %>% mutate(FiscalYear = ifelse(....))

# str_pad does not work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using some regex you could do:

library(dplyr)

df |> 
  mutate(FiscalYear = gsub("\\-(\\d)", "- \\1", FiscalYear))
#>    id  FiscalYear
#> 1   1 2012 - 2013
#> 2   2 2012 - 2013
#> 3   3 2012 - 2013
#> 4   4 2012 - 2013
#> 5   5 2012 - 2013
#> 6   6 2014 - 2015
#> 7   7 2014 - 2015
#> 8   8 2014 - 2015
#> 9   9 2014 - 2015
#> 10 10 2014 - 2015
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading