I have two numeric columns. One contains a year, one a month number. I want to join these two and make a Year-month column that is of the proper Date type. To give a background, the reason I can't keep it as a character type is that I am plotting these points. They don't sort properly if they are char. For example, instead of
2015 1
2015 2
...
2015 12
We would see the sort order as
2015 1
2015 10
2015 11
2015 12
...
So if there is some kind of character hack that works the same as a conversion to a Date type, that will work too.
Sorry for this relatively simple question. I am ok with R but struggle with formatting.
Sample code for re-creating
month<-as.character(seq(1,12,1))
year<-'2015'
df<-data.frame(paste(year,month))
In order to be a proper date type, you need a month, day, and year. I usually just throw a "1" in there for the day, since every month has a first day...
df <- data.frame(year=c("2015", "2015", "2014"),
month=c("4", "2", "9"),
stringsAsFactors=FALSE)
df$date <- as.Date(paste(df$month, "01", df$year, sep="_"), format="%m_%d_%Y")
df <- df[order(df$date), ]
您可以考虑在Zoo软件包中使用yearmon类:
library(zoo) zoo::as.yearmon(paste(year, month, sep='-'))
只需在粘贴中添加01
并使用as.Date
as.Date(paste(year, month, '01', sep= '-'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.