【发布时间】:2019-05-06 11:07:26
【问题描述】:
【问题讨论】:
-
请不要使用代码图片。以可重复的形式包含数据,例如使用
dput(data)并包含输出
标签: r date datatable lubridate
【问题讨论】:
dput(data) 并包含输出
标签: r date datatable lubridate
base解决方案:
f = "%m/%d/%y" # note the lowercase y; it's because the year is 92, not 1992
dataset$SetDateMonth <- format(as.POSIXct(dataset$SetDate, format = f), "%m")
基本上,它的作用是将列从character(假定类)转换为POSIXct,这样可以轻松提取月份信息。
快速测试:
format(as.POSIXct('1/1/92', format = "%m/%d/%y"), "%m")
[1] "01"
【讨论】:
试试这个(创建了一个小例子):
library(lubridate)
date_example <- "1/1/92"
lubridate::mdy(date_example)
[1] "1992-01-01"
lubridate::mdy(date_example) %>% lubridate::month()
[1] 1
如果要将整月作为字符串,请使用:
lubridate::mdy(date_example) %>% lubridate::month(label = TRUE, abbr = FALSE)
【讨论】: