dateTime changes from POSIXct to factor when averaging - R

I have the following example:

begin_date = as.POSIXlt("1990-01-01", tz = "GMT")
# 30 year dataset
dat = data.frame(dateTime = begin_date + (0:(24*30*20)) * (1800))
dat = within(dat,{speed = runif(length(dateTime), 1, 10)
})

I wish to calculate the hourly averages, so I use:

data <- aggregate(dat[colnames(dat)[2:length(colnames(dat))]],
                  list(dateTime = cut(dat$dateTime,breaks = "hour")),
                  mean,
                  na.rm = TRUE)

However, the class of the dateTime column has changed from POSIXct to factor:

> class(dat$dateTime)
[1] "POSIXct" "POSIXt" 
> class(data$dateTime)
[1] "factor"

Why is this the case, and how can I change it back to be POSIXct?

Answers


 data$dateTime <- as.POSIXct(as.character( data$dateTime)) 

You can make the hourly bins using seq and findInterval

rng <- range(dat$dateTime)
rng[1] <- rng[1] - (as.numeric(rng[1]) %% 3600) #subtract remainder after div by 3600    secs
hrs <- seq(rng[1],rng[2],by="hour") #sequence by hour
bins <- hrs[findInterval(dat$dateTime, hrs)] #identify the start of hourly interval for each row in dat

then use bins instead of cut

data <- aggregate(dat[colnames(dat)[2:length(colnames(dat))]],
                  list(dateTime = bins),
                  mean,
                  na.rm = TRUE)

> class(dat$dateTime)
[1] "POSIXct" "POSIXt" 

> class(data$dateTime)
[1] "POSIXct" "POSIXt" 

Need Your Help

css box model does not stretch using padding

html css layout css-float

I have a project title as a header in my webpage. This project title is within a div called "pagetitle". After the project title, i have two words which one has to be on the left and another on the

What would be the simplest way to alpha sort an array of chars in C?

c arrays sorting character

I'm looking for a simple, easy to understand algorithm to alphabetically sort an array of characters in C.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.