如果我们有一个实际包含日期值的整数列,例如2020年9月29日为20200929,则可以通过使用转换函数将其转换为日期,方法是使用as.Date函数读取日期,但是还需要as.character,以便as.Date函数可以读取日期值。
请看以下数据帧-
ID<−1:20 Dates<−c(20200101, 20200401, 20201015, 20200111, 20200222, 20200121, 20200701, 20201231, 20200417, 20200601, 20200811, 20200927, 20200512, 20200713, 20200225, 20200324, 20200203, 20200819, 20200916, 20200428) df1<−data.frame(ID,Dates) df1
输出结果
ID Dates 1 1 20200101 2 2 20200401 3 3 20201015 4 4 20200111 5 5 20200222 6 6 20200121 7 7 20200701 8 8 20201231 9 9 20200417 10 10 20200601 11 11 20200811 12 12 20200927 13 13 20200512 14 14 20200713 15 15 20200225 16 16 20200324 17 17 20200203 18 18 20200819 19 19 20200916 20 20 20200428
将日期转换为适当的日期格式-
df1<−transform(df1,Dates=as.Date(as.character(Dates),"%Y%m%d")) df1
输出结果
ID Dates 1 1 2020−01−01 2 2 2020−04−01 3 3 2020−10−15 4 4 2020−01−11 5 5 2020−02−22 6 6 2020−01−21 7 7 2020−07−01 8 8 2020−12−31 9 9 2020−04−17 10 10 2020−06−01 11 11 2020−08−11 12 12 2020−09−27 13 13 2020−05−12 14 14 2020−07−13 15 15 2020−02−25 16 16 2020−03−24 17 17 2020−02−03 18 18 2020−08−19 19 19 2020−09−16 20 20 2020−04−28
S.NO<−1:20 Date<−c(19980313, 19980604, 19980409, 19980104, 19980501, 19980101, 19980521, 19980412, 19980601, 19980711, 19980615, 19980810, 19980509, 19980221, 19981101, 19981121, 19981009, 19980915, 19980929, 19980813) df2<−data.frame(S.NO,Date) df2
输出结果
S.NO Date 1 1 19980313 2 2 19980604 3 3 19980409 4 4 19980104 5 5 19980501 6 6 19980101 7 7 19980521 8 8 19980412 9 9 19980601 10 10 19980711 11 11 19980615 12 12 19980810 13 13 19980509 14 14 19980221 15 15 19981101 16 16 19981121 17 17 19981009 18 18 19980915 19 19 19980929 20 20 19980813
将日期转换为适当的日期格式-
df2<−transform(df2,Date=as.Date(as.character(Date),"%Y%m%d")) df2
输出结果
S.NO Date 1 1 1998−03−13 2 2 1998−06−04 3 3 1998−04−09 4 4 1998−01−04 5 5 1998−05−01 6 6 1998−01−01 7 7 1998−05−21 8 8 1998−04−12 9 9 1998−06−01 10 10 1998−07−11 11 11 1998−06−15 12 12 1998−08−10 13 13 1998−05−09 14 14 1998−02−21 15 15 1998−11−01 16 16 1998−11−21 17 17 1998−10−09 18 18 1998−09−15 19 19 1998−09−29 20 20 1998−08−13