R中字符和数字列的日期

问题描述

我有一个格式设置的数据集。如何将它们合并到日期格式列?

year   mon  day  

1997    Jul   3   
1997    Jul   1   
1997    Sep   10   
1997    Sep   1     
1998    Oct   10      

解决方法

您可以paste一起放在三列中,并使用as.Date将其转换为日期:

df <- transform(df,date = as.Date(paste(year,mon,day),'%Y %b %d'))

还可以使用ymd中的lubridate

library(dplyr)
library(lubridate)

df %>% mutate(date = ymd(paste(year,day)))

#  year mon day       date
#1 1997 Jul   3 1997-07-03
#2 1997 Jul   1 1997-07-01
#3 1997 Sep  10 1997-09-10
#4 1997 Sep   1 1997-09-01
#5 1998 Oct  10 1998-10-10

数据

df <- structure(list(year = c(1997L,1997L,1998L),mon = c("Jul","Jul","Sep","Oct"),day = c(3L,1L,10L,10L)),class = "data.frame",row.names = c(NA,-5L))
,

使用concat(format(price,'en_us'),'$') 软件包对@Ronak Shah进行类似的回答

anytime

数据

library(dplyr)
library(anytime)
library(stringr)
df %>% 
  mutate(year_mon_date = anydate(str_c(V1,V2,V3)))
           
#     V1  V2 V3 year_mon_date
# 1 1997 Jul  3    1997-07-03
# 2 1997 Jul  1    1997-07-01
# 3 1997 Sep 10    1997-09-10
# 4 1997 Sep  1    1997-09-01
# 5 1998 Oct 10    1998-10-10 
,

您可以使用make_date()中的lubridate

library(dplyr)
library(lubridate)

df %>%
  mutate(date = make_date(year,match(mon,month.abb),day))

#   year mon day       date
# 1 1997 Jul   3 1997-07-03
# 2 1997 Jul   1 1997-07-01
# 3 1997 Sep  10 1997-09-10
# 4 1997 Sep   1 1997-09-01
# 5 1998 Oct  10 1998-10-10

其中month.abb是一个内置向量,用于存储英文月份名称的缩写。


数据

df <- structure(list(year = c(1997L,-5L))