简体   繁体   English

连接两个数字列以创建Year-month变量

[英]Join two numeric columns to create a Year-month variable

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. 我想将这两部分合并,并创建一个具有正确日期类型的Year-month列。 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. 如果是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. 我对R没问题,但是在格式方面很挣扎。

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... 我通常每天都会在其中输入“ 1”,因为每个月都有第一天...

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= '-'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM