Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

Convert Factor to Date/Time in R

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...