r - calculate daily averages for 3d array -
is possible perform daily averaging on 3d array in r?
for example:
i have 3d array of data points on lat/lon grid 2 days.
lat <- 50:51 lon <- 2:3 time <- as.posixct(c('2009-01-01 12:00','2009-01-01 15:00','2009-01-01 17:00','2009-01-02 12:00', '2009-01-02 16:00')) j <- array(c(1:6, 11:16, 21:26), c(2,2,5)) dim(j) [1] 2 2 5
where first dimension refers latitude, second refers longitude, , third refers time (i.e. data @ each lat/lon through time).
how calculate daily averages of these values , return daily averaged 3d array?
the return array should have dimensions of
dim(j) [1] 2 2 2
where time dimensions correspond to:
new_time <- as.posixct(c('2009-01-01','2009-01-02))
is possible?
without taking account different days, can perform 3d averaging with:
apply(j, c(1,2), mean)
but i'm unsure on how perform averaging on selected days.
any appreciated.
ok make sure, in example, there 5 days, right?
if want select days, e.g, 1st, 3rd , 5th, can specify them follows:
> apply(j[,,c(1,3,5)], c(1,2), mean) [,1] [,2] [1,] 13 6.333333 [2,] 14 7.333333
edit
ok, here work around:
library(purrr) library(lubridate)
if interested in unique days:
# days tx <- day(time) > tx [1] 1 1 1 2 2
get unique days , count them:
# unique days txu <- unique(tx) # number of unique days d <- length(unique(tx))
create dataframe hold data
# create df days df <- data.frame(day=1:d)
find indecies of entries corresponding each days , add them in new column
# add column entries corresponding each days df <- df %>% mutate(days_entries=map(day, function(x) which(tx %in% txu[x]) )) > df day days_entries 1 1 1, 2, 3 2 2 4, 5
add means of values each day in new column
df <- df %>% mutate(day_mean=map(days_entries, {function(x) apply(j[,,x], c(1,2), mean)} ) )
put means in 1 array:
> k <- array( c( sapply(df$day_mean, function(x) x)) , dim = c( 2 ,2 ,d ) ) > dim(k) [1] 2 2 2 > k , , 1 [,1] [,2] [1,] 6.333333 9.666667 [2,] 7.333333 10.666667 , , 2 [,1] [,2] [1,] 23 12 [2,] 24 13
Comments
Post a Comment