我正在进行与雪相关的研究,并且每小时有雪高数据。
我想创建一个表示一天积雪高度变化的变量,最好通过计算当天MAX值和第一次测量值之间的差值来近似。
我提出的下一个最佳解决方案是使用summaryBY通过提取MAX和MIN来计算MAX和MIN之间的差异 - 代码如下所示:
snowheight_change<-summaryBy(data=sh_hourly, snowheight ~ date, FUN=c(max, min), na.rm=TRUE)
但它不准确,有没有办法使用summaryBy
提取24小时测量中的第一个?
答案 0 :(得分:0)
你可以尝试:
set.seed(49)
sh_hourly <- data.frame(date=seq(as.POSIXct("2008-02-04"), length.out=40, by='1 hour'), snowheight=sample(1:25,40,replace=TRUE))
library(data.table)
setDT(sh_hourly)[, date1:= as.Date(date)][,
list(snowheight=max(snowheight)-snowheight[1]), by=date1]
# date1 snowheight
#1: 2008-02-04 15
#2: 2008-02-05 12
library(doBy)
使用之前未转换为sh_hourly
data.table
sh_hourly$date1 <- as.Date(sh_hourly$date)
res <- summaryBy(data=sh_hourly, snowheight ~ date1, FUN=max)
res[,2] <- res[,2]-sh_hourly$snowheight[firstobs(~date1, sh_hourly)]
res
# date1 snowheight.max
#1 2008-02-04 15
#2 2008-02-05 12