如何在R中对时间值进行分类

时间:2015-10-11 20:08:02

标签: r

如何在R中将时间值分类为月份桶? 现在

time                     
2014-01-31 20:46 +0000   
2014-01-31 10:46 +0000   
2014-02-21 20:16 +0000   
2014-02-11 12:36 +0000   

我的目标

time                     month
2014-01-31 20:46 +0000   Jan
2014-01-31 10:46 +0000   Jan
2014-02-21 20:16 +0000   Feb
2014-02-11 12:36 +0000   Feb

2 个答案:

答案 0 :(得分:1)

time <- c("2014-01-31 20:46 +0000",   
          "2014-01-31 10:46 +0000",   
          "2014-02-21 20:16 +0000",   
          "2014-02-11 12:36 +0000")

library(lubridate)
# first convert it to a proper date-time format and put it in a dataframe
df <- as.data.frame(as.POSIXct(time))
#then simply calculate month
df$month <- month(time, label= TRUE)

给出了:

      as.POSIXct(time)  month
1 2014-01-31 20:46:00   Jan
2 2014-01-31 10:46:00   Jan
3 2014-02-21 20:16:00   Feb
4 2014-02-11 12:36:00   Feb

答案 1 :(得分:0)

这是我的方法:

data <- read.csv("~/data.csv", 
                header=TRUE, 
                dec=".", 
                sep=",", 
                stringsAsFactors=FALSE)


time <- data$time
time <- as.Date(time, format="%Y-%m-%d %H:%M")
time


data$year <- as.factor(format(time, format ="%Y"))
data$month <- as.factor(format(time, format ="%m"))
data$day <- as.factor(format(time, format ="%d"))