Reputation: 1111
I have a lot of different dates in one column of my dataframe. I would like to aggregate the data so that only the year is kept; I do not need months and days. Originally the entries were saved as integer
. The function as.Date
returns nonsense
"0011-06-20"
instead of
"11-06-2000"
So I used as.character.Date
and got valid results:
as.character.Date(Training_lowNA$last_swap)
[1] "11/6/2000 "
From these results I now want to erase the day and the month, only keeping the year. Or would it have been easier to do the same with integers?
I would be glad if there was a helpful idea around!
EDIT: my input data has 50,000 entries of dates of the format
[9955] 8/14/2001 5/27/2001 3/16/2001 4/13/2000
[9961] 7/1/2000 5/18/2000 8/6/2001 7/17/2000 9/16/2001
[9967] 10/21/2000 7/24/2001 5/6/2000 12/18/2000
[9973] 1/11/2001 7/31/2001 9/17/2001 3/8/2001
[9979] 9/30/2000 7/12/2001 8/20/2000
[9985] 10/20/2000 9/21/2000 9/27/2000 7/18/2000
[9991] 10/1/2000
[9997] 9/17/2001 7/22/2001 11/6/2000 5/31/2001
[ reached getOption("max.print") -- omitted 40000 entries ]
What I would like as output is:
[9955] 2001 2001 2001 2000
[9961] 2000 2000 2001 2000 2001
[9967] 2000 2001 2000 2000
[9973] 2001 2001 2001 2001
[9979] 2000 2001 2000
[9985] 2000 2000 2000 2000
[9991] 2000
[9997] 2001 2001 2000 2001
EDIT #2
As David suggested below, I tried his approach:
Training_lowNA[] <- lapply(Training_lowNA, function(x) format(as.Date(x, "%m/%d/%Y"), "%Y")).
the debug shows:
function (x)
{
xx <- x[1L]
if (is.na(xx)) {
j <- 1L
while (is.na(xx) && (j <- j + 1L) <= length(x)) xx <- x[j]
if (is.na(xx))
f <- "%Y-%m-%d"
}
if (is.na(xx) || !is.na(strptime(xx, f <- "%Y-%m-%d", tz = "GMT")) ||
!is.na(strptime(xx, f <- "%Y/%m/%d", tz = "GMT")))
return(strptime(x, f))
stop("character string is not in a standard unambiguous format")
and here comes EDIT #3:
> dput(head(Training_lowNA$last_swap))
structure(c(78L, 32L, 1100L, 1019L, 522L, 265L), .Label = c("",
"1/1/2000", "1/1/2001", "1/1/2002", "1/10/1999", "1/10/2000",
"here follow 50,000 entries of this sort", "9/9/2000", "9/9/2001"
), class = "factor")
Upvotes: 1
Views: 938
Reputation: 4921
The following would do it:
dat <- c("8/14/2001", "5/27/2001", "3/16/2001", "4/13/2000", "7/1/2000", "5/18/2000", "8/6/2001", "7/17/2000", "9/16/2001", "10/21/2000", "7/24/2001", "7/24/1977", "7/24/1999")
ndat <- as.POSIXlt(dat, format="%m/%d/%Y")
as.POSIXlt(ndat)$year + 1900
Upvotes: 0
Reputation: 1664
First thing, you need to make proper date object from string:
(a <- as.Date("9/21/2000", "%m/%d/%Y"))
## [1] "2000-09-21"
Then you can extract year with:
format(a, "%Y")
## [1] "2000"
Which combines into one-liner, given you have vector with date:
format(as.Date(df$date, "%m/%d/%Y"), "%Y")
Upvotes: 2