我在一个房间里有一些关于几天的CO2值的实验数据,这些数据都有时间和日期戳。我想把它分成一系列的“实验”,基于每个实验发生的时间的实验列表。

例如:
数据
df<-data.frame(CO2.ppm.=runif(10), Date.time.=as.POSIXct(" 2019-2-08 07:00:00") + runif(n=10, min=0, max=3600))开始和停止时间的实验列表:
ExpertimentList<- data.frame(StartTime=c("2019-2-08 07:10:00", "2019-2-08 07:15:00", "2019-2-08 08:30:00"), StopTime=c("2019-2-08 07:12:00","2019-2-08 07:16:00","2019-2-08 08:15:00"),ExptID=c(1,2,3))请注意,有时会测量到CO2,但未进行任何实验。例如,在07:12:00和07:15:00之间。
我想分开
由
%s
和
到目前为止,我已经将所有内容转换为整数
df$Date.time.<-as.integer(df$Date.time.)
ExperimentList$StartTime<-as.integer(ExperimentList$StartTime
ExperimentList$StopTime<-as.integer(ExperimentList$StopTime)然后看着
breakz<-dplyr::arrange(paste(Experiment_List$StartTime,Experiment_List$StopTime)%>%as_tibble())
cut(df$Dev.Date.Time,breaks=unique(breakz$value))但是当没有实验发生的时候,我不能过滤掉数据。任何想法都是非常感谢的。
预期输出:
set.seed(143)
data.frame(CO2.ppm.=runif(10), Date.time.=sort(as.POSIXct(" 2019-2-08 07:00:00") + runif(n=10, min=0, max=3600)),ExptID=c(NA,NA,NA,1,NA,NA,NA,NA,NA,NA))答案:
我发现@Ronak的答案会耗尽内存,所以我把data.frame分成了10000个行段:
df<-split(df, (as.numeric(rownames(df))-1) %/% 10000)然后根据@Ronak的回答,我将代码弹出到一个函数中,并使用并行包中的mclapply。
#执行左连接以删除任何不属于实验的行
fuzzyJoinFunction<-function(a){
a<-fuzzy_left_join(a, Experiment_List,
by = c('Dev.Date.Time' = 'StartTime', 'Dev.Date.Time'= 'StopTime'),
match_fun = c(`>=`, `<=`))
a
}
df<-rbindlist(mclapply(X=df,FUN=fuzzyJoinFunction,mc.cores=4))发布于 2021-03-01 20:48:46
我们可以使用
仅保留范围内的行。
library(dplyr)
library(fuzzyjoin)
#All the datetime values should be of type POSIXct.
ExpertimentList %>%
mutate(across(c(StartTime, StopTime), lubridate::ymd_hms)) -> ExpertimentList
fuzzy_inner_join(df, ExpertimentList,
by = c('Date.time.' = 'StartTime', 'Date.time.'= 'StopTime'),
match_fun = c(`>=`, `<=`))获取所有
最终输出中的值
对于
使用
..。
https://stackoverflow.com/questions/66421855
复制相似问题