将因子转换为R中的日期/时间 [英] Convert Factor to Date/Time in R
问题描述
这是我的数据框中包含的信息:
## minuteofday:factor w / 89501 levels2013-06- 01 08:07:00,...
## dDdt:num 7.8564 2.318 ...
##分钟:POSIXlt,格式:NA NA NA
我需要将日分栏转换为日期/时间格式:
minuteave $ minutes< - as.POSIXlt(as.character(minuteave $ minuteofday),format =%m /%d /%Y%H:%M:%S)
我尝试过 as.POSIXlt
, as.POSIXct
和 as.Date
。没有一个工作。有没有人有任何想法。
目标是绘制分钟与dDdt,但不会让我在指定的时间段内绘制我想作为因子。我不知道接下来要尝试什么...
你需要插入一个 as.character ()
在解析为日期时间或日期之前。
一个因素将始终作为与其级别相对应的数字返回。 >
您可以通过将 read.csv()
等作为因素来保存从因素到字符的转换: code> stringsAsFactors = FALSE 。您也可以将其设置为全局选项。
将其作为字符后,请确保您将格式字符串与您的数据匹配:
R> as.POSIXct(2013-06-01 08:07:00,format =%Y-%m-%d%H:%M:%S)
[1]2013-06- 01 08:07:00 CDT
R>
请注意%Y-%m-%d
我使用,而不是你的%m /%d /%y
。
编辑于2016年1月3日:由于随时包括从许多类型(包括 factor
)自动转换,并且不需要格式字符串
R> as.factor(2013-06-01 08:07:00)
[1] 2013-06-01 08:07:00
级别:2013-06-01 08:07:00
R>
R>图书馆(任何时间)
R> anytime(as.factor(2013-06-01 08:07:00))
[1]2013-06-01 08:07:00 CDT
R>
R> class(anytime(as.factor(2013-06-01 08:07:00)))
[1]POSIXctPOSIXt
R>
正如你所看到的,我们只是将因子变量加入到 anytime() / code>,并输出所需的POSIXct类型。
This is the information contained within my dataframe:
## minuteofday: factor w/ 89501 levels "2013-06-01 08:07:00",...
## dDdt: num 7.8564 2.318 ...
## minutes: POSIXlt, format: NA NA NA
I need to convert the minute of day column to a date/time format:
minuteave$minutes <- as.POSIXlt(as.character(minuteave$minuteofday), format="%m/%d/%Y %H:%M:%S")
I've tried as.POSIXlt
, as.POSIXct
and as.Date
. None of which worked. Does anyone have ANY thoughts.
The goal is to plot minutes vs. dDdt, but it won't let me plot in the specified time period that I want to as a factor. I have no idea what to try next...
You need to insert an as.character()
before parsing as a Datetime or Date.
A factor will always come back first as a number corresponding to its level.
You can save the conversion from factor to character by telling read.csv()
etc to no store as a factor: stringsAsFactors=FALSE
. You can also set that as a global option.
Once you have it as character, make sure you match the format string to your data:
R> as.POSIXct("2013-06-01 08:07:00", format="%Y-%m-%d %H:%M:%S")
[1] "2013-06-01 08:07:00 CDT"
R>
Note the %Y-%m-%d
I used, as opposed to your %m/%d/%y
.
Edit on 3 Jan 2016: This is now much easier thanks to the anytime package which automagically converts from many types, including factor
, and does so without requiring a format string.
R> as.factor("2013-06-01 08:07:00")
[1] 2013-06-01 08:07:00
Levels: 2013-06-01 08:07:00
R>
R> library(anytime)
R> anytime(as.factor("2013-06-01 08:07:00"))
[1] "2013-06-01 08:07:00 CDT"
R>
R> class(anytime(as.factor("2013-06-01 08:07:00")))
[1] "POSIXct" "POSIXt"
R>
As you can see we just feed the factor variable into anytime()
and out comes the desired POSIXct type.
这篇关于将因子转换为R中的日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!