简体   繁体   中英

how can I add a white space within a characther vector in r?

I have a sequence of dates in character ("2018-09-032018-09-09" "2018-09-102018-09-16" .....) and I would add a white space after the 10th digit. As a final result, I would obtain the following "2018-09-03 2018-09-09" "2018-09-10 2018-09-16"... I guess the gsub fuction can help but I don't know how to implement it
Could you please help me ?

We could use str_extract_all with this '\\\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])' regex which is for YYYY-MM-DD format:

library(stringr)
unlist(str_extract_all(dates, '\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])'))

output:

 "2018-09-03" "2018-09-09" "2018-09-10" "2018-09-16"

Does this work:

gsub('(.{10})(.*)','\\1 \\2' ,c("2018-09-032018-09-09", "2018-09-102018-09-16"))
[1] "2018-09-03 2018-09-09" "2018-09-10 2018-09-16"

We can use sub to capture the first 10 digits and then add the space

sub("^(.{10})(.*)", "\\1 \\2", dates)

-output

[1] "2018-09-03 2018-09-09" "2018-09-10 2018-09-16"

NOTE: We used sub and that was only necessary along with the fact that i specified the start ( ^ ) character.

data

dates <- c("2018-09-032018-09-09", "2018-09-102018-09-16")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM