如何从R中的日期中提取月份 [英] How to extract Month from date in R
问题描述
我正在使用lubridate
包并应用month
函数从日期中提取月份.我在日期字段上运行了str命令,我得到了
I am using the lubridate
package and applying the month
function to extract month from date. I ran the str command on date field and I got
Factor w/ 9498 levels "01/01/1979","01/01/1980",..: 5305 1 1 1 1 1 1 1 1 1 ...
> v1$Date<-month(v1$Date)
Error in as.POSIXlt.character(as.character(x), ...) :
character string is not in a standard unambiguous format
这是我的数据框示例
https://drive.google.com/file/d/0B6cqWmwsEk20Q2dHblhXZi14Wk0/edit?usp =共享
我不知道我在做什么错.
I don't know what I am doing wrong.
推荐答案
?month
状态:
日期时间必须是POSIXct,POSIXlt,日期,时间段,时间,年份, yearqtr,zoo,zooreg,timeDate,xts,其,ti,jul,timeSeries和fts 对象.
Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
您的对象是一个因素,甚至不是字符向量(可能是由于stringsAsFactors = TRUE
所致).您必须将向量转换为某个日期时间类,例如转换为POSIXlt
:
Your object is a factor, not even a character vector (presumably because of stringsAsFactors = TRUE
). You have to convert your vector to some datetime class, for instance to POSIXlt
:
library(lubridate)
some_date <- c("01/02/1979", "03/04/1980")
month(as.POSIXlt(some_date, format="%d/%m/%Y"))
[1] 2 4
还有一个便捷功能dmy
,可以执行相同的操作(@Henrik提出的提示):
There's also a convenience function dmy
, that can do the same (tip proposed by @Henrik):
month(dmy(some_date))
[1] 2 4
更进一步,@ IShouldBuyABoat还提供了另一个提示,即接受dd/mm/yyyy字符格式而无需任何显式强制转换:
Going even further, @IShouldBuyABoat gives another hint that dd/mm/yyyy character formats are accepted without any explicit casting:
month(some_date)
[1] 2 4
有关格式的列表,请参见?strptime
.您会发现标准明确格式"代表
For a list of formats, see ?strptime
. You'll find that "standard unambiguous format" stands for
默认格式遵循ISO 8601国际标准 该标准将日期表示为"2001-02-28",将时间表示为 "14:01:02"在此处使用前导零.
The default formats follow the rules of the ISO 8601 international standard which expresses a day as "2001-02-28" and a time as "14:01:02" using leading zeroes as here.
这篇关于如何从R中的日期中提取月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!