我一直在閱讀類似的文章我無法使任何解決方案適用於我的案例(可能是因爲我是R新手)。將數據框中的日期與其他數據框中的兩個日期進行比較
我有一個很長的數據集,有幾個參數,其中一個是日期,另一個數據框的日期間隔與特定的值相對應。我試圖讓重複的例子:
df = data.frame(date=c("2017/08/01 19:00:00","2017/08/01 19:10:00","2017/08/01 19:20:00","2017/08/01 19:30:00",
"2017/08/01 19:40:00","2017/08/01 19:50:00","2017/08/01 20:00:00","2017/08/01 20:10:00"),
factor1=c(10,15,11,13,14,12,16,15))
df2 = data.frame(start=c("2017/08/01 19:00:00","2017/08/01 19:40:00"),
end=c("2017/08/01 19:15:00","2017/08/01 20:05:00"), factor2=c("A","B"))
df$date <- as.POSIXct(df$date)
df2$start <- as.POSIXct(df2$start)
df2$end <- as.POSIXct(df2$end)
而結果我想是這樣的:
result = data.frame(date=c("2017/08/01 19:00:00","2017/08/01 19:10:00","2017/08/01 19:20:00","2017/08/01 19:30:00",
"2017/08/01 19:40:00","2017/08/01 19:50:00","2017/08/01 20:00:00","2017/08/01 20:10:00"),
factor1=c(10,15,11,13,14,12,16,15),factor2=c("A","A","NA","NA","B","B","B","NA"))
我試着用ifelse:
ifelse(df$date >= df2$start & df$date <= df2$end,df2$factor2,"NA")
但不能做這行得通。
有什麼建議嗎?
它與原始數據完美配合!謝謝!!! <3 <3 – NeReiS
乾杯!樂於幫助 –