2012-03-07 48 views
0

df是年內戰鬥事件&衝突。我試圖計算衝突年份內戰鬥之間的平均距離(時間)。分組事件之間的平均時間距離

頭看起來是這樣的:

conflictId | year | event_date | event_type 
107   1997 1997-01-01 1 
107   1997 1997-01-01 1 
20   1997 1997-01-01 1 
20   1997 1997-01-01 2 
20   1997 1997-01-03 1 

是我第一次嘗試是

time_prev_total <- aggregate (event_date ~ conflictId + year, data, diff)

,但我最終event_date是在新的DF列表。試圖在df內提取列表的第一個索引位置是不成功的。

另外有人建議我說,我可以創建每個衝突一年內的時間索引,那麼滯後該索引,創建一個新的數據幀與conflictIdyearevent_date和滯後指標,然後合併,與原始df,但將新df中的滯後索引與原始df中的舊索引匹配。我試圖實現這一點,但我有點不確定如何索引obs。在衝突年份之內,因爲它是不平衡的。

+0

沒有可重現的數據,很難知道問題出在哪裏。請提供一小部分數據。這樣做有兩個方面:1)它幫助您更輕鬆2)使您的問題更易於其他未來的搜索者 – 2012-03-07 20:55:55

+0

對此感到抱歉,我似乎無法讓Tab工作,因此我可以用適當的方式對其進行格式化。我假設我在這裏做了一些類型的新手錯誤。 – Zach 2012-03-07 21:08:40

+0

沒關係。您可以使用索引選擇一些行:'x < - dat [c(1,2,3,10,11,12)]''然後使用'dput(x)'爲我們提供可重現的數據。如果你需要更多的幫助,打開另一個線程並提出要求,因爲提供可重複的數據將使你獲得目標結果。 – 2012-03-07 21:12:07

回答

2

您可以使用ddply將數據幀拆分爲 (每年一個衝突)並對每個應用函數。

# Sample data 
n <- 100 
d <- data.frame(
    conflictId = sample(1:3,  n, replace=TRUE), 
    year  = sample(1990:2000, n, replace=TRUE), 
    event_date = sample(0:364,  n, replace=TRUE), 
    event_type = sample(1:10,  n, replace=TRUE) 
) 
d$event_date <- as.Date(ISOdate(d$year,1,1)) + d$event_date 
library(plyr) 

# Average distance between battles, within each year and conflict 
ddply(
    d, 
    c("year","conflictId"), 
    summarize, 
    average = mean(dist(event_date)) 
) 

# Average distance between consecutive battles, within each year and conflict 
d <- d[order(d$event_date),] 
ddply(
    d, 
    c("year","conflictId"), 
    summarize, 
    average = mean(diff(event_date)) 
) 
+0

你是一個紳士和學者。非常感謝你! – Zach 2012-03-08 00:06:42