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
571 views
in Technique[技术] by (71.8m points)

r - Combining date and time into a Date column for plotting

I want to create a line plot. I have 3 columns in my data frame:

date        time   numbers
01-02-2010  14:57  5
01-02-2010  23:23  7
02-02-2010  05:05  3
02-02-2010  10:23  11

How can I combine the first two columns and make a plot based on date and time ? Date is Date class, time is just a char variable.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The lubridate package is another option. It handles most of the fussy formatting details, so it can be easier to use than base R date functions. For example, in your case, mdy_hm (month-day-year_hour-minute) will convert your date and time variables into a single POSIXct date-time column. (If you meant it to be day-month-year, rather than month-day-year, then just use dmy_hm.) See code below.

library(lubridate)

dat$date_time = mdy_hm(paste(dat$date, dat$time))

dat
        date  time numbers           date_time
1 01-02-2010 14:57       5 2010-01-02 14:57:00
2 01-02-2010 23:23       7 2010-01-02 23:23:00
3 02-02-2010 05:05       3 2010-02-02 05:05:00
4 02-02-2010 10:23      11 2010-02-02 10:23:00

library(ggplot2)
ggplot(dat, aes(date_time, numbers)) + 
  geom_point() + geom_line() +
  scale_x_datetime(breaks=date_breaks("1 week"),
                   minor_breaks=date_breaks("1 day"))

enter image description here


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

...