user6678274 user6678274 - 3 months ago 19
R Question

Converting to date in R

In R I have

data


1/1/2014
1/1/2014
....
4/14/2016


I want a new dataset
data_new
that contain all entries with year 2016.
When I type
as.Date(data)
I get
"1-01-20" "1-01-20" ...
which I don't understand. How can I make this subset?

Answer

Since you did as.Date(data), I am assuming data to be a character vector.


Use year <- substring(as.Date(data, "%m/%d/%Y"), 1L, 4L) to extract year information, then use subset(data, year == "2016") to get subset.


Why not simply use grep("2016", data, value = TRUE)?