I have 3 columns: month, day, and year. They are all in integer format. For example, in one row, year == 2013, month == 1, day == 1. I need to use these 3 columns to create a new column that says what day of the week it is (i.e. Tuesday). Thanks.
Asked
Active
Viewed 67 times
0
-
@Vlo Their date is all one column though and hyphenated. I have 3 columns in my table, each seperate with year, month, and day. – skatofia Jan 26 '18 at 18:42
-
1Paste the columns together with paste0() – Vlo Jan 26 '18 at 18:54
-
@Vlo I figured it out with the lubridate package thanks! – skatofia Jan 26 '18 at 19:08
1 Answers
0
This should help you to derive date from 3 columns. Solution usages base
libraries
# sample data to demonstrate conversion. Dates are random
df <- data.frame(year = c(2018, 2016, 2017, 2018),
month = c(7:10),
day = c(9:12) )
df
# year month day
# 1 2018 7 9
# 2 2016 8 10
# 3 2017 9 11
# 4 2018 10 12
# Convert and add additional column as date. Use of paste and sprintf.
df$date <- as.Date(paste(df$year, sprintf("%02d",df$month), sprintf("%02d", df$day) , sep = "-"), "%Y-%m-%d")
# Find and populate date-of-week
df$day_of_week <- weekdays(df$date)
#Result:
df
# year month day date day_of_week
# 1 2018 7 9 2018-07-09 Monday
# 2 2016 8 10 2016-08-10 Wednesday
# 3 2017 9 11 2017-09-11 Monday
# 4 2018 10 12 2018-10-12 Friday

MKR
- 19,739
- 4
- 23
- 33