Home > Back-end >  Add space after - in a value when there is no space after it
Add space after - in a value when there is no space after it

Time:11-05

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

CodePudding user response:

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
  • Related