我有30个传感器的CO2测量数据,这些传感器不是同时测量,也不是完全在同一时间启动。我想尽可能地使它们对齐,因此我认为平均10s可能是一个很好的解决方案。
在上一个问题:Group by multiple variables and summarise dplyr中,我将每个传感器的时间缩减为10s,并平均每个传感器在这10s内的读数。听起来不错,但是我已经意识到,以下代码从每个传感器开始的时间开始就缩短了时间,因此它们仍未对齐。如何对齐它们?
dist
我尝试过:
require(tidyverse)
require(lubridate)
df %>%
group_by(Sensor, BinnedTime = cut(DeviceTime, breaks="10 sec")) %>%
mutate(Concentration = mean(calCO2)) %>%
ungroup()
head(df)
# A tibble: 6 x 7
# Groups: BinnedTime [1]
Sensor Date Time calCO2 DeviceTime cuts BinnedTime
<fctr> <date> <time> <dbl> <dttm> <fctr> <chr>
1 N1 2019-02-12 13:24 400 2019-02-12 13:24:02 (0,10] 2019-02-12 13:24:02
2 N1 2019-02-12 13:24 400 2019-02-12 13:24:02 (0,10] 2019-02-12 13:24:02
3 N1 2019-02-12 13:24 400 2019-02-12 13:24:03 (0,10] 2019-02-12 13:24:03
4 N2 2019-02-12 13:24 400 2019-02-12 13:24:03 (0,10] 2019-02-12 13:24:02
5 N3 2019-02-12 13:24 400 2019-02-12 13:24:03 (0,10] 2019-02-12 13:24:02
6 N3 2019-02-12 13:24 400 2019-02-12 13:24:05 (0,10] 2019-02-12 13:24:04
但是它给出了一个错误,说x必须是数字,所以我将dt<-seq(
from=as.POSIXct("2019-02-12 13:24:00", tz="GMT"),
to=as.POSIXct("2019-02-12 14:00:00", tz="GMT"),
by="10 sec"
)
cut(df$BinnedTime,dt)
和df$BinnedTime
都转换为数字,这只会产生NA。
dt$dt
我想念什么?
我有以下内容:
cut(as.numeric(as.POSIXct(df$BinnedTime)), as.numeric(dt))
我想这就是我追求的目标,但它并不优雅。
这是一个驱动器中的数据文件:df.txt until 30th March 19
答案 0 :(得分:2)
library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#>
#> date
df <- read_delim("https://gist.githubusercontent.com/ramiromagno/4347eefec2aa36ec94423b75b145fccb/raw/5c1b445686bd014ea3a1f0336433e3b364779766/df.txt", delim = " ", col_types = cols())
df$DeviceTime <- as.POSIXct(paste(df$Date, df$Time), format="%Y-%m-%d %H:%M:%S")
dt <- seq(
from = as.POSIXct("2019-02-12 13:24:00", tz = "GMT"),
to = as.POSIXct("2019-02-12 14:00:00", tz = "GMT"),
by = "10 sec"
)
df %>%
mutate(BinnedTime = cut(DeviceTime, breaks=dt)) %>%
group_by(Sensor)%>%
group_by(BinnedTime,add=TRUE)%>%
summarize(calCO2 = mean(na.omit(calCO2))) -> df2
df2
#> # A tibble: 7,557 x 3
#> # Groups: Sensor [?]
#> Sensor BinnedTime calCO2
#> <chr> <fct> <dbl>
#> 1 A1 2019-02-12 13:24:00 400
#> 2 A1 2019-02-12 13:24:10 401
#> 3 A1 2019-02-12 13:24:20 401
#> 4 A1 2019-02-12 13:24:30 401
#> 5 A1 2019-02-12 13:24:40 401
#> 6 A1 2019-02-12 13:24:50 400
#> 7 A1 2019-02-12 13:25:00 400
#> 8 A1 2019-02-12 13:25:10 398
#> 9 A1 2019-02-12 13:25:20 397
#> 10 A1 2019-02-12 13:25:30 394
#> # ... with 7,547 more rows