I would like R to recognize one column as date. It is read as factor during the import, however, when I try to format with 'as.Date' and 'format' I only get NAs. I'm not sure where I'm going wrong.
> d = read.table("ByMonth.Year_54428.txt", header=T, sep=",")
> str(d)
'data.frame': 607 obs. of 2 variables:
$ V1 : Factor w/ 607 levels "1950-12","1951-01",..: 1 2 3 4 5 6 7 8 9 10 ...
$ Rain: int 100 56000 29293 37740 19649 41436 58067 51082 49629 62680 ...
>
>
> Date.form1 <- as.Date(d$V1, "%Y-%m")
> str(Date.form1)
Date[1:607], format: NA NA NA NA NA NA NA NA NA NA NA NA NA NA ...
>
> Date.form2 = as.Date(as.character(d$V1), format="%Y-%m")
> str(Date.form2)
Date[1:607], format: NA NA NA NA NA NA NA NA NA NA NA NA NA NA ...
MM. yyyy — Example: 23.06. 2013. dd/MM/yyyy — Example: 23/06/2013.
YYYY/MMM/DD. Four-digit year, separator, three-letter abbreviation of the month, separator, two-digit day (example: 2003/JUL/25) DD/MMM/YYYY. Two-digit day, separator, three-letter abbreviation of the month, separator, four-digit year (example: 25/JUL/2003)
The MMMM format for months is the full name of the Month. For example -January, February, March, April, May, etc are the MMMM Format for the Month.
A year and a month do not make a date. You need a day also.
d <- data.frame(V1=c("1950-12","1951-01"))
as.Date(paste(d$V1,1,sep="-"),"%Y-%m-%d")
# [1] "1950-12-01" "1951-01-01"
You could also use the yearmon
class in the zoo package.
library(zoo)
as.yearmon(d$V1)
# [1] "Dec 1950" "Jan 1951"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With