R 计算3d阵列的每日平均值
是否可以对R中的3d阵列执行每日平均 例如: 我在lat/lon网格上有两天的3d数据点阵列R 计算3d阵列的每日平均值,r,R,是否可以对R中的3d阵列执行每日平均 例如: 我在lat/lon网格上有两天的3d数据点阵列 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
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
但我不确定如何在选定的天数内进行平均
任何帮助都将不胜感激 确定一下,在您的示例中,有5天,对吗
如果要选择某些日期,例如,第一天、第三天和第五天,可以按如下方式指定它们:
> apply(j[,,c(1,3,5)], c(1,2), mean)
[,1] [,2]
[1,] 13 6.333333
[2,] 14 7.333333
编辑
好的,这里有一个解决方法:
library(purrr)
library(lubridate)
如果您对独特的日子感兴趣:
# get days
tx <- day(time)
> tx
[1] 1 1 1 2 2
#获取天数
发送
[1] 1 1 1 2 2
获取唯一的天数并计算它们:
# unique days
txu <- unique(tx)
# number of unique days
d <- length(unique(tx))
#唯一的天数
徐克
1.
[,1] [,2]
[1,] 6.333333 9.666667
[2,] 7.333333 10.666667
2.
[,1] [,2]
[1,] 23 12
[2,] 24 13
重塑数据并使用常用的拆分-应用组合函数。我不希望重塑数据,因为事实上,数据位于0.25度分辨率的全局网格上,因此会变得相当大。那么,您要么使用低效循环,要么使用Rcpp编写一些内容。如果可以的话,我会先尝试一下。在这个例子中有两天的时间。看时间戳。你误解了这个问题。是的,我误解了,请检查编辑后的答案。我希望这次我拿到了。
# get days
tx <- day(time)
> tx
[1] 1 1 1 2 2
# unique days
txu <- unique(tx)
# number of unique days
d <- length(unique(tx))
# create a df with days
df <- data.frame(day=1:d)
# add a column with entries corresponding to 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
df <- df %>%
mutate(day_mean=map(days_entries,
{function(x) apply(j[,,x], c(1,2), mean)}
)
)
> 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