0

I have a data table that looks roughly like the following:

Date_Time               Water_Level        Date
6-28-2019 15:00:00         184             6-28-2019
6-28-2019 15:15:00         186             6-28-2019
6-28-2019 15:30:00         180             6-28-2019
6-29-2019 10:15:00         179             6-29-2019
6-29-2019 10:30:00         188             6-29-2019
6-29-2019 10:45:00         190             6-29-2019

I'd like to be able to use the aggregate function to find the daily average water level for the entire data set so it looks something like this:

Date_Time       Water_Level
6-28-2019          183.3
6-29-2019          185.6

I used the following code, but for some reason it only aggregated SOME of the data, not all of it. If I switch the Date_Time column out for the Date column (second code below), it does the job, but the dates are out of order resulting in me needing to run a line to reorder them...

LSUP1<-aggregate(Water_Level_m~Date_Time, LSUP, mean)
LSUP1<-LSUP1[order(as.Date(LSUP1$Date, format="%m/%d/%Y")),]

I'm also having some trouble extracting the "day of year" (DOY) from the POSIXct format of the Date_Time column. I aggregated some similar data based on DOY and that worked swimmingly...

Any suggestions would be lovely, even if it's a different function.

Katy
  • 41
  • 3

1 Answers1

1

Sure:

R> now
[1] "2020-02-18 15:58:10.226131 CST"
R> class(now)
[1] "POSIXct" "POSIXt" 
R> unclass(as.POSIXlt(now))
$sec
[1] 10.2261

$min
[1] 58

$hour
[1] 15

$mday
[1] 18

$mon
[1] 1

$year
[1] 120

$wday
[1] 2

$yday
[1] 48

$isdst
[1] 0

$zone
[1] "CST"

$gmtoff
[1] -21600

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

The preferred way, though, is through the standard time formatter functions. Day of the year is %j per help(sptrftime):

R> format(now, "%j")
[1] "049"
R> 

These functions are all vectorized, and it is easy to call as.integer() or as numeric on them:

R> as.integer(format(as.Date(now) + cumsum(runif(5)*20), "%j"))
[1] 61 65 84 96 99
R> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725