Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems formatting date into format "%Y-%m" [duplicate]

Tags:

r

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 ...
like image 920
KG12 Avatar asked May 06 '13 15:05

KG12


People also ask

How do you write the date in MM YY format?

MM. yyyy — Example: 23.06. 2013. dd/MM/yyyy — Example: 23/06/2013.

What is yyyy mmm dd format?

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)

What is MMM date format?

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.


1 Answers

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"
like image 161
Joshua Ulrich Avatar answered Oct 10 '22 06:10

Joshua Ulrich