如何将月份日和年份列转换为星期几

时间:2018-01-26 18:31:47

标签: r

我有3列:月,日和年。它们都是整数格式。例如,在一行中,year == 2013,month == 1,day == 1.我需要使用这3列来创建一个新列,该列说明它是星期几(即星期二)。感谢。

1 个答案:

答案 0 :(得分:0)

这可以帮助您从3列中获取日期。解决方案使用base

# 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