这是lubridate包装中的一种方法。
> getMethod("month<-")
Method Definition (Class "derivedDefaultMethod"):
function (x, value)
{
if (!is.numeric(value)) {
value <- pmatch(tolower(value), c("january", "february",
"march", "june", "july", "august", "september", "october",
"november", "december"))
}
x <- x + months(value - month(x))
}
Run Code Online (Sandbox Code Playgroud)
我的问题是+运算符的最后一行。运算符的行为取决于的类别x。R如何知道要这样做?我如何查看其源代码+?
> library(lubridate)
>
> customFUN <- function (x, value){
+ x <- x + months(value - month(x))
+ return(x)
+ }
>
>
> init_datePOSIX <- as.POSIXct("2017-11-01")
> init_dateDate <- as.Date("2017-11-01")
>
> customFUN(init_datePOSIX, 12) …Run Code Online (Sandbox Code Playgroud) 我有一个带有日期时间列的数据框。我想将该列拆分为多列:year、month、day、time_12、time_24和timezone。
和需要分别是使用 12 小时约定和 24 小时约定的字符向量time_12。time_24我怎样才能做到这一点?
library(tidyverse)
library(lubridate)
# data frame
myDates <- ymd_hm(c('2018-October-31 8:00 PM',
'2018Oct31T20:00'))
df <- data.frame(datetime = myDates)
# split datetime into parts
df$year <- year(df$datetime)
df$month <- month(df$datetime)
df$day <- day(df$datetime)
df$time_12 <- '8:00 PM' ### need help
df$time_24 <- '20:00' ### need help
df$tz <- tz(df$datetime)
df
# datetime year month day time_12 time_24 tz
# 1 2018-10-31 …Run Code Online (Sandbox Code Playgroud)