Skip to content
Prev 361635 / 398506 Next

create an empty data frame and then fill in it (and then evaluate the mean of semi-hourly data for each day)

Finally I applied lapply in this way:
df_snow_day$snow <- lapply(df_snow_day$day, function(x)
round(mean(df_snow$snow[df_snow$day == x], na.rm=T))

This does not work. I do not understand why the class of df_snow_day$snow
is of type list either:


lapply()'s output is always a list.

            I first created a new column of type "Date"
            df_snow$day <- as.Date(df_snow$data_POSIX,"%Y-%m-%d")

If 'date_POSIX' is of class "POSIXct" that line gives a warning because
the second argument to as.Data.POSIXct is the time zone ('tz').
Perhaps your data_POSIX column is really character.  I made my df_snow
as follows:

txt <- c("data_POSIX\tsnow",
  "2004-11-01 00:00:00\t50",
  "2004-11-01 00:30:00\t55",
 "2004-11-01 01:00:00\t60")
df_snow <- read.table(sep="\t", text=txt,header=TRUE,
colClasses=c("POSIXct","numeric"))
str(df_snow)
'data.frame':   3 obs. of  2 variables:
 $ data_POSIX: POSIXct, format: "2004-11-01 00:00:00" ...
 $ snow      : num  50 55 60

and as.Date gave:
   > as.Date(df_snow$data_POSIX,"%Y-%m-%d")
   [1] "2004-11-01" "2004-11-01" "2004-11-01"
   Warning message:
   In as.POSIXlt.POSIXct(x, tz = tz) : unknown timezone '%Y-%m-%d'

Also, converting POSIXct objects to Date objects is usually the wrong
thing to do, as the time zone in the POSIXct object is ignored (I think UTC
is assumed):
  > ct <- as.POSIXct(sprintf("2016-%02d-%02d %02d:%02d", 2:5, 22:25, 15:18,
45:48), tz="US/Pacific")
  > data.frame(ct,as.Date(ct)) # note day-of-month mismatches
                     ct as.Date.ct.
  1 2016-02-22 15:45:00  2016-02-22
  2 2016-03-23 16:46:00  2016-03-23
  3 2016-04-24 17:47:00  2016-04-25
  4 2016-05-25 18:48:00  2016-05-26
You can convert to a POSIXlt object and pull out the day-of-month
or day-of-year
  > as.POSIXlt(ct)$mday
  [1] 22 23 24 25
  > as.POSIXlt(ct)$yday
  [1]  52  82 114 145
I can never remember which helper functions are available
for this sort of thing.  Many people like the ones in the lubridate
package.

Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Fri, Jun 10, 2016 at 3:45 AM, Stefano Sofia <
stefano.sofia at regione.marche.it> wrote: