- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert year, month, and day of the month into a complete date in R?
To convert year, month, and day of the month into a complete date, we can follow the below steps −
- Create a data frame with Year, Month and DayOfMonth as separate columns.
- Use mutate function of dplyr package to create complete date.
Create the data frame
Let's create a data frame as shown below −
Year<-sample(c(2001,2002,2003,2004,2005,2006,2007,2008),25,replace=TRUE) Month<-sample(1:12,25,replace=TRUE) DayOfMonth<-sample(1:30,25,replace=TRUE) df<-data.frame(Year,Month,DayOfMonth) df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
Year Month DayOfMonth 1 2007 4 26 2 2003 4 4 3 2001 1 12 4 2002 4 26 5 2003 3 17 6 2005 9 22 7 2002 4 4 8 2005 12 23 9 2003 2 12 10 2003 2 26 11 2004 8 15 12 2002 3 10 13 2004 5 27 14 2005 8 2 15 2002 3 16 16 2008 5 29 17 2003 9 23 18 2003 7 24 19 2006 7 4 20 2001 8 14 21 2005 3 6 22 2002 6 27 23 2004 4 19 24 2004 6 21 25 2001 7 13
Convert Year, Month, and DayOfMonth into a complete date
Use mutate function of dplyr package to create complete date with Year, Month, and DayOfMonth −
Year<-sample(c(2001,2002,2003,2004,2005,2006,2007,2008),25,replace=TRUE) Month<-sample(1:12,25,replace=TRUE) DayOfMonth<-sample(1:30,25,replace=TRUE) df<-data.frame(Year,Month,DayOfMonth) library(dplyr) df %>% mutate(df,Dates=paste(Year,Month,DayOfMonth,sep="/"))
Output
Year Month DayOfMonth Dates 1 2007 4 26 2007/4/26 2 2003 4 4 2003/4/4 3 2001 1 12 2001/1/12 4 2002 4 26 2002/4/26 5 2003 3 17 2003/3/17 6 2005 9 22 2005/9/22 7 2002 4 4 2002/4/4 8 2005 12 23 2005/12/23 9 2003 2 12 2003/2/12 10 2003 2 26 2003/2/26 11 2004 8 15 2004/8/15 12 2002 3 10 2002/3/10 13 2004 5 27 2004/5/27 14 2005 8 2 2005/8/2 15 2002 3 16 2002/3/16 16 2008 5 29 2008/5/29 17 2003 9 23 2003/9/23 18 2003 7 24 2003/7/24 19 2006 7 4 2006/7/4 20 2001 8 14 2001/8/14 21 2005 3 6 2005/3/6 22 2002 6 27 2002/6/27 23 2004 4 19 2004/4/19 24 2004 6 21 2004/6/21 25 2001 7 13 2001/7/13
Advertisements