简体   繁体   English

改进一个 function 来提取年、月和星期几

[英]Improve a function to extract year, month and date of week

I'd like to write a wrap function where I can reduce the steps to extract year, month and day of the week, so I don't have to repeartly put down the date variable name.我想写一个 wrap function ,我可以减少提取年、月和星期几的步骤,这样我就不必重复输入日期变量名。 Also if I need extra seasonal variable or some other time object line, I can just add extra line in the function.此外,如果我需要额外的季节性变量或其他时间 object 行,我可以在 function 中添加额外的行。

The line by line way is逐行方式是

library(lubridate)
yr = year(travel_date)
mth = months(travel_date)
day = weekdays(travel_date))

I can chain them through a dplyr way:我可以通过dplyr方式链接它们:

cat <- cat %>% mutate(yr = year(travel_date), 
                      mth = months(travel_date),
                      day = weekdays(travel_date))

The data.table way: data.table方式:

cat[, yr := year(travel_date)][, mnth := months(travel_date)][, dayweek := weekdays(travel_date)]

My wrap function idea is that I only need to put down the dataframe name and the variable name once.我的wrap function思路是只需要记一次dataframe的名字和变量名。 But it's not working.但它不起作用。

time_spin <- function(x, y) {
  x[, yr := year(y)][,mth := months(y)][,day := weekdays(y)]
}

Any suggestion I can improve this?有什么建议我可以改进吗? I can take a wrap function through dplyr or data.table .我可以通过 function 到dplyrdata.table换行。

dput输入

cat <- structure(list(id = 1:6, 
                      travel_date = structure(c(16107L, 17266L, 16834L, 17953L, 17953L, 17953L), 
                                              class = c("IDate", "Date"))), 
                 row.names = c(NA, -6L), 
                 class = c("data.table", "data.frame"))

Using dplyr you can write the function as:使用dplyr可以将 function 写成:

time_spin <- function(x, y) {
  x %>% mutate(yr = year(.data[[y]]), 
                 mth = months(.data[[y]]),
                 day = weekdays(.data[[y]]))
}

time_spin(cat, 'travel_date')

#   id travel_date   yr      mth       day
#1:  1  2014-02-06 2014 February  Thursday
#2:  2  2017-04-10 2017    April    Monday
#3:  3  2016-02-03 2016 February Wednesday
#4:  4  2019-02-26 2019 February   Tuesday
#5:  5  2019-02-26 2019 February   Tuesday
#6:  6  2019-02-26 2019 February   Tuesday

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM