r语言 - 计算20秒间隔的平均值,并按另一列分组



我正在处理在海象潜水期间收集的不同变量的大型数据集。我想以精细的尺度(20秒间隔)分析我的数据。我想把数据分成20秒的间隔,基本上我只想得到每20秒的平均值,这样我就可以对这些数据间隔进行更多的分析。但是,我需要按潜水#对数据进行分组,这样我就不会从单独的潜水中收集信息。

到目前为止,我已经尝试了三种方法:

  • period.apply(),但我无法与此功能分组
  • split()通过潜水#来子集我的数据,但似乎找不到一种方法来计算的平均值
  • openair包,使用timeaverage(),但继续得到一个错误(见下面的代码)。

下面是我尝试过的数据和代码。我想要每20秒窗口的深度,MSA, rate_s和HR的方法-按diveNum分组,理想情况下也是D_phase。

> head(seal_dives)
datetime   seal_ID  Depth    MSA        D_phase diveNum rate_s     HR
1 2018-04-06 14:47:51  Congaree  4.5    0.20154042       D       1     NA     115.3846
2 2018-04-06 14:47:51  Congaree  4.5    0.20154042       D       1     NA     117.6471
3 2018-04-06 14:47:52  Congaree  4.5    0.11496760       D       1     NA     115.3846
4 2018-04-06 14:47:52  Congaree  4.5    0.11496760       D       1     NA     122.4490
5 2018-04-06 14:47:53  Congaree  4.5    0.05935992       D       1     NA     113.2075
6 2018-04-06 14:47:53  Congaree  4.5    0.05935992       D       1     NA     113.2075
#openair package using timeaverage, results in error message
> library(openair)
> seal_20<-timeAverage(
seal_dives,
avg.time = "20 sec",
data.thresh = 0,
statistic = "mean",
type = c("diveNum","D_phase"),
percentile = NA,
start.date = NA,
end.date = NA,
vector.ws = FALSE,
fill = FALSE
)
Can't find the variable(s) date 
Error in checkPrep(mydata, vars, type = "default", remove.calm = FALSE,  : 

#converting to time series and using period.apply(), but can't find a way to group them by dive #, or use split() then convert to time series.
#create a time series data class from our data frame
> seal_dives$datetime<-as.POSIXct(seal_dives$datetime,tz="GMT")
> seal_xts <- xts(seal_dives, order.by=seal_dives[,1])
> seal_20<-period.apply(seal_xts$Depth, endpoints(seal_xts$datetime, "seconds", 20),  mean)
#split data by dive # but don't know how to do averages over 20 seconds
> seal_split<-split(seal_dives, seal_dives$diveNum)

也许有一种神奇的方法可以做到这一点,我还没有在网上找到,或者也许我只是在我的方法中做错了什么。

您可以使用floor_date函数从lubridate到bin数据每20秒。将它们与diveNumD_phase一起分组,以获得使用across的其他列的平均值。

library(dplyr)
library(lubridate)
result <- df %>%
group_by(diveNum, D_phase, datetime = floor_date(datetime, '20 sec')) %>%
summarise(across(c(Depth, MSA, rate_s, HR), mean, na.rm = TRUE), .groups = 'drop')
result

最新更新