2014-03-26 26 views
3

很久以前我已經問過這個問題,但還沒有找到答案。我不知道這是否合法在stackoverflow,但我轉發它。findInterval()在data.table中有不同的間隔R

我在R中有一個data.table,我想創建一個新的列,查找相應年份/月份的每個價格的時間間隔。

重複的例子:

set.seed(100) 
DT <- data.table(year=2000:2009, month=1:10, price=runif(5*26^2)*100) 
intervals <- list(year=2000:2009, month=1:10, interval = sort(round(runif(9)*100))) 
intervals <- replicate(10, (sample(10:100,100, replace=T))) 
intervals <- t(apply(intervals, 1, sort)) 
intervals.dt <- data.table(intervals) 
intervals.dt[, c("year", "month") := list(rep(2000:2009, each=10), 1:10)] 
setkey(intervals.dt, year, month) 
setkey(DT, year, month) 

我剛纔想:

  • 合併DTintervals.dt data.tables按月/年,
  • 創建一個新的intervalsstring列由所有的V *列到 一列字符串,(不是很優雅,我承認),最後
  • 它substringing爲載體,所以我可以在findInterval()使用它,但該解決方案並不爲每個行工作

所以,後(!):

DT <- merge(DT, intervals.dt) 
DT <- DT[, intervalsstring := paste(V1, V2, V3, V4, V5, V6, V7, V8, V9, V10)] 
DT <- DT[, c("V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10") := NULL] 
DT[, interval := findInterval(price, strsplit(intervalsstring, " ")[[1]])] 

我得到

> DT 
     year month  price    intervalsstring interval 
    1: 2000  1 30.776611 12 21 36 46 48 51 63 72 91 95  2 
    2: 2000  1 62.499648 12 21 36 46 48 51 63 72 91 95  6 
    3: 2000  1 53.581115 12 21 36 46 48 51 63 72 91 95  6 
    4: 2000  1 48.830599 12 21 36 46 48 51 63 72 91 95  5 
    5: 2000  1 33.066053 12 21 36 46 48 51 63 72 91 95  2 
---                
3376: 2009 10 33.635924 12 40 45 48 50 65 75 90 96 97  2 
3377: 2009 10 38.993769 12 40 45 48 50 65 75 90 96 97  3 
3378: 2009 10 75.065820 12 40 45 48 50 65 75 90 96 97  8 
3379: 2009 10 6.277403 12 40 45 48 50 65 75 90 96 97  0 
3380: 2009 10 64.189162 12 40 45 48 50 65 75 90 96 97  7 

這是正確的第一行,但而不是爲最後(或其他)行。 例如,對於第3380行,價格〜64.19應該在第5個區間而不是第7個區間。我想我的錯誤是,通過我的最後一個命令,找到間隔只依賴intervalsstring的第一行。

謝謝!

+0

你看過'?data.table'並確保你理解每一個參數嗎?我只是簡單地看了一下這個問題,我的第一個想法是想知道你是否知道'roll','',也許''foverlaps()'。 –

回答

8

你的主要問題是你沒有爲每個組做findInterval。但我也沒有看到將這個大型合併data.tablepaste/strsplit業務的重點。這是我會做的:

DT[, interval := findInterval(price, 
           intervals.dt[.BY][, V1:V10, with = F]), 
    by = .(year, month)][] 
#  year month  price interval 
# 1: 2000  1 30.776611  2 
# 2: 2000  1 62.499648  6 
# 3: 2000  1 53.581115  6 
# 4: 2000  1 48.830599  5 
# 5: 2000  1 33.066053  2 
# ---        
#3376: 2009 10 33.635924  1 
#3377: 2009 10 38.993769  1 
#3378: 2009 10 75.065820  7 
#3379: 2009 10 6.277403  0 
#3380: 2009 10 64.189162  5 

請注意,intervals.dt[.BY]是一個鍵控子集。

+1

不錯'.BY'的例子。添加到https://github.com/Rdatatable/data.table/issues/1363。 –