根据以下数据,如何在特殊字符-
后面添加空格?我知道我必须使用gsub
,但它总是让我感到困惑,所以请解释一下。
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 = " "))
在tidyverse
中,值随mutate
而更改。这些更改是此函数的参数。
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
创建于2022-11-04,reprex v2.0.2