[R] Using dates in R

David L Carlson dcarlson at tamu.edu
Wed Mar 4 20:08:30 CET 2015


Wow! A bold prediction from someone who has done exactly zero investigation of the basic, built-in date/time features in R. Since your example did not include the first two digits of the year, I've used %y instead of %Y. That will assume "19" precedes values from 69-99 and "20" precedes values from 00 to 68. If you decide to implement this with a for loop, it means you have much more to learn.

> today <- "3/4/15"
> d1 <- "2/15/80"
> d2 <- "2/15/16"
> # Is d before today, if so 0, otherwise 1
> as.integer(strptime(today, "%m/%d/%y") < strptime(d1, "%m/%d/%y"))
[1] 0
> as.integer(strptime(today, "%m/%d/%y") < strptime(d2, "%m/%d/%y"))
[1] 1

?strptime for details

-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352


-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Brian Hamel
Sent: Wednesday, March 4, 2015 8:55 AM
To: r-help at r-project.org
Subject: [R] Using dates in R

Hi all,

I have a dataset that includes a "date" variable. Each observation includes
a date in the form of 2/15/15, for example. I'm looking to create a new
indicator variable that is based on the date variable. So, for example, if
the date is earlier than today, I would need a "0" in the new column, and a
"1" otherwise. Note that my dataset includes dates from 1979-2012, so it is
not one-year (this means I can't easily create a new variable 1-365).

How does R handle dates? My hunch is "not well," but perhaps there is a
package that can help me with this. Let me know if you have any
recommendations as to how this can be done relatively easily.

Thanks! Appreciate it.

Best,
Brian

	[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list