[英]Loop through dataframe in R and measure time difference between two values
[英]Conditional merging between time values of 2 dataframe in R
我有2個具有不同結構的數據框。 第一個包含來自連續樣本和對幾個樣本進行重復分析的數據(多行,每個單次測量都有時間和值),第二個報告樣本ID以及測量的開始和結束時間。
##example
df.analysis <- data.frame(var= rnorm(321,mean=50),
time= seq(strptime("2018-1-1 0:0:0","%Y-%m-%d %H:%M:%S"), strptime("2018-1-1 8:0:0","%Y-%m-%d %H:%M:%S"), by= 90))
df.sample <- data.frame(sample= rep_len(1:8, 30),
start=seq(strptime("2018-1-1 0:0:0","%Y-%m-%d %H:%M:%S"), strptime("2018-1-1 7:45:0","%Y-%m-%d %H:%M:%S"),length.out=30),
end=seq(strptime("2018-1-1 0:15:0","%Y-%m-%d %H:%M:%S"), strptime("2018-1-1 8:0:0","%Y-%m-%d %H:%M:%S"),length.out=30))
我應該插入與每個測量值相對應的樣品ID,請注意並非所有測量都與一個樣品相對應。 我嘗試使用以下代碼,但是它不起作用,因為現在它將第一個數據庫中的行與第二個數據庫中的對應行進行比較。 雖然我需要將第一個數據庫中的每一行與第二個數據庫中的所有行進行比較
if df.analysis$time >df.sample[,"start"] & df.analysis$time < df.sample[,"end"] {
df.analysis$sample <- df.sample$sample
}
我lapply
想使用for
循環或lapply
但無法正常使用它們。
我們可以使用非等額聯接
library(data.table)
setDT(df.analysis)[df.sample, sample := sample, on = .(time > start, time <end)]
使用sqldf
軟件包的一個選項可以通過具有inner join
sqldf
然后具有left outer join
sqldf
方式來實現:
library(sqldf)
sqldf("select analysis.*, matchedSample.sample from
'df.analysis' analysis
left outer join
(select sample.sample, analysis.time
from 'df.sample' sample,'df.analysis' analysis
where analysis.time > sample.start
and analysis.time < sample.end) matchedSample on
analysis.time = matchedSample.time")
# var time sample
# 1 49.41763 2018-01-01 00:00:00 NA
# 2 50.20399 2018-01-01 00:01:30 1
# 3 48.80242 2018-01-01 00:03:00 1
# 4 50.56982 2018-01-01 00:04:30 1
# 5 50.08948 2018-01-01 00:06:00 1
# 6 50.32223 2018-01-01 00:07:30 1
# 7 49.60842 2018-01-01 00:09:00 1
# 8 50.82316 2018-01-01 00:10:30 1
# ....
# .... 313 more rows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.