Home > Back-end >  Add space after - in a value
Add space after - in a value

Time:11-05

Based on the data below how can I add a space after the special character - ? 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",
               "2012 -2013", "2012 -2013", "2012 -2013", "2012 -2013", "2012 -2013")
# Sample
df = data.frame(id, FiscalYear)

# Updated Sample
df_new = df %>% gsub....

# str_pad does not work
df_updated = df %>% with(stringr::str_pad(FiscalYear, width = 6, pad = " "))

CodePudding user response:

In the tidyverse, values are changed with mutate. The changes are arguments to this function.

suppressPackageStartupMessages(
  library(dplyr)
)

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

# Updated Sample
df_new <- df %>% 
  mutate(FiscalYear = sub("-", "- ", FiscalYear))

df_new  
#>    id  FiscalYear
#> 1   1 2012 - 2013
#> 2   2 2012 - 2013
#> 3   3 2012 - 2013
#> 4   4 2012 - 2013
#> 5   5 2012 - 2013
#> 6   6 2012 - 2013
#> 7   7 2012 - 2013
#> 8   8 2012 - 2013
#> 9   9 2012 - 2013
#> 10 10 2012 - 2013

Created on 2022-11-04 with reprex v2.0.2

  • Related