简体   繁体   English

R更改月份/合并日期和年份向量

[英]R Change Month / Combine Date & Year Vectors

I have a dataset that has three columns: month, day, and year. 我有一个包含三列的数据集:月,日和年。 The month is a character vector and shows the month name in full. 月是一个字符向量,并完整显示月名称。 The day and year vectors are both numeric. 日和年向量都是数字。 I need to convert the month names to their respective number and then combine all three columns to make a full date ("mm-dd-yy"). 我需要将月份名称转换为它们各自的编号,然后将所有三列组合成一个完整的日期(“ mm-dd-yy”)。 I have tried to use lubridate, but have not had success. 我尝试使用lubridate,但没有成功。 Here is an example of my dataset: 这是我的数据集的一个示例:

Month      Day      Year
JANUARY    1        1980

Thanks. 谢谢。

You could try 你可以试试

v1 <-  do.call(paste, df1)
as.Date(v1, '%B %d %Y')

Or using lubridate 或使用lubridate

library(lubridate)
mdy(v1)

Or 要么

 mdy(sprintf('%s %s %s', df1$Month, df1$Day, df1$Year))

Or you can use do.call with sprintf 或者您可以在sprintf使用do.call

 mdy(do.call(sprintf, c(df1, list('%s %s %s'))))

this works: 这有效:

your data example : 您的数据示例:

df<-(read.table(text="
Month Day Year 
JANUARY 1 1980", header=T))



as.Date(paste(df$Month, df$Day, df$Year), format="%b %d %Y")

#"1980-01-01"

Since you already have the month/day/year separated into separate fields, straight up string manipulation may be a bit faster than converting to time/date classes and back: 由于您已经将月/日/年划分为单独的字段,因此直接进行字符串操作可能比转换为时间/日期类并返回转换要快一些:

MONTHS <- c('JANUARY',
'FEBRUARY',
'MARCH',
'APRIL',
'MAY',
'JUNE',
'JULY',
'AUGUST',
'SEPTEMBER',
'OCTOBER',
'NOVEMBER',
'DECEMBER')

library(stringr)
paste(str_pad(paste(match(myData$Month,MONTHS)), 2, side = "left", pad = "0"),
      str_pad(myData$Day, 2, side = "left", pad = "0"),
      substr(myData$Year,3,4),
      sep = '-')

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

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