Alex Bădoi
Alex Bădoi

Reputation: 830

How to merge and unmerge a character vector?

I need to keep track of my data through a series of calculations.

i have the following vectors:

start_date <- "2010-11-04"
end_date <- "2010-11-10"

i wish to merge them into a single character vector that looks like this

"2010-11-04 to 2010-11-10"

then i would like the inverse:

from: "2010-11-04 to 2010-11-10" back to the original two vectors

Upvotes: 1

Views: 103

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269461

This does not use any packages:

p <- paste(start_date, "to", end_date)
p
## [1] "2010-11-04 to 2010-11-10"

Going in the other direction remove everything after the first space to get the string representing the first date and remove everything up to the last space to get the string representing the second date:

sub(" .*", "", p)
## [1] "2010-11-04"
sub(".* ", "", p)
## [1] "2010-11-10"

An alternative is to split the string using strsplit:

s <- unlist(strsplit(p, " to "))
s
## [1] "2010-11-04" "2010-11-10"

so s[1] is the string representing the first date and s[2] is the string representing the second date.

UPDATE: Modified as per Richard Scriven's comment.

Upvotes: 3

Related Questions