
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Data Frame Column to Date in R
If we have an integer column that actually contains date values, for example having 29th September 2020 as 20200929 then we can convert it to date by using transform function by reading the dates with as.Date function but as.character will also be needed so that as.Date function can read the date values.
Example1
Consider the below data frame −
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
Output
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
Converting Dates to appropriate date format −
df1<−transform(df1,Dates=as.Date(as.character(Dates),"%Y%m%d")) df1
Output
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
Example2
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
Output
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
Converting Date to appropriate date format −
df2<−transform(df2,Date=as.Date(as.character(Date),"%Y%m%d")) df2
Output
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
Advertisements