首页 > 解决方案 > rbind() 用于 posixct 值并在函数仅处理一天时找到 2 天内的平均值?

问题描述

我正在寻找解决2个问题:

  1. 我有好几天的每小时数据。鉴于这个每小时数据,我试图通过近似每日数据的整体曲线,将数据点的数量从每天 24 个点减少到 4 个点。每日曲线如下所示:

https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.researchgate.net%2Ffigure%2FTop-hat-function-with-all-spatial-frequencies-present-in-its- Fourier-spectrum-green-and_fig1_276466464&psig=AOvVaw1lP8xuSKbh9YUm61cC3i8M&ust=1628033180521000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCMiL4q--k_ICFQAAAAAdAAAAAAAD

我写了一个函数来逼近给定 1 天数据的曲线。但是,我希望估算一年的数据价值,因此我希望有一个晚上的平均值来反映第 1 天晚上和第 2 天早上的平均值,而不是第 1 天晚上的平均值。目前我的晚上平均值只给了我第 1 天晚上的平均值,因为我的函数每天只从 i=2:24 读取每小时数据。我的最终目标是使用带有 day=1:365 的 for 循环来获得全年的简化曲线,不确定是否有更好的方法来做到这一点......

  1. 对于我的输出变量new_x,我试图使用melt() 在同一个图表上绘制x 和new_x,但是由于日期的POSIXCT 值,我无法使用rbind() 合并new_x 和x。有没有办法可以 ggplot 两个变量?

谢谢,

# A function to return the top hat function, given a 24 by 2 vector x 
tophat <- function(x){
delta <- matrix(0,nrow=24,ncol=1)

for (i in 2:24){
  # i-th element is the i-th hour per day
  delta[i] = x[i,2]-x[i-1,2]
}

# Find hour at which max and min daily values occur
a1 <- which.max(delta)
b1 <- which.min(delta)-1
peak <- mean(x[a1:b1,2]) # peak value
am <- mean(x[1:(a1-1),2]) # morning average value
pm <- mean(x[(b1+1):24,2]) # evening average value

new_time <- c(x[(a1-1),1],x[a1,1],x[b1,1],x[(b1+1),1])
new_values <- c(am, peak, peak, pm)
new_x <- data.frame(new_time, new_values)

z <- data.frame(x, new_x) 
#z %>% melt(id="time") %>% ggplot(aes(x=time, y=value, colour=variable)) + geom_point() + geom_line() + theme(axis.text.x = element_text(angle = 90)) + scale_x_datetime(date_breaks = "1 hour")
}

#dput(x) gives the following
structure(list(time = structure(c(1451606400, 1451610000, 1451613600, 
1451617200, 1451620800, 1451624400, 1451628000, 1451631600, 1451635200, 
1451638800, 1451642400, 1451646000, 1451649600, 1451653200, 1451656800, 
1451660400, 1451664000, 1451667600, 1451671200, 1451674800, 1451678400, 
1451682000, 1451685600, 1451689200), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), Crow_education_Omer = c(0.0173731172095063, 
0.0175417882503753, 0.0175839560105925, 0.017499620490158, 0.0173309494492891, 
0.017668291531027, 0.017836962571896, 0.017836962571896, 0.0182586401740685, 
0.0234452746807901, 0.0250476495690455, 0.0253428238905662, 0.0252163206099145, 
0.025975340293825, 0.0260175080540422, 0.0260175080540422, 0.0253428238905662, 
0.025975340293825, 0.0252163206099145, 0.0184273112149375, 0.017668291531027, 
0.0176261237708098, 0.0175839560105925, 0.0174152849697235)), row.names = c(NA, 
24L), class = "data.frame")

标签: rggplot2averagerbind

解决方案


推荐阅读