2017-10-11 70 views
0

通過選擇條件的多個行我有數據集的以下提取物:中的R

extract[989:993, ] 
# A tibble: 5 x 2 
    Dates    `Rating agency` 
    <dttm>    <chr> 
1 2014-07-11    NA 
2 2014-07-14    NA 
3 2014-07-15   DBRS 
4 2014-07-16    NA 
5 2014-07-17    NA 

我想選擇的時間間隔[-1:1],其對應於前一天和後的第二天降級。在「評級機構」欄不是「NA」欄的行表示發生了降級。在我上面的例子中,rows [990:992]。

我的數據集包含45276個條目,其中536個降級(列「評級機構」不是「NA」),我希望構建一個包含3行的列表,其中降級介於這樣的整個數據集之間:

extract[990:992, ] 
# A tibble: 3 x 2 
    Dates   `Rating agency` 
    <dttm>   <chr> 
1 2014-07-14    NA 
2 2014-07-15   DBRS 
3 2014-07-16    NA 

我用這個命令試了一下:

interval1 <- basisanddowngradessingledates[`Rating agency` != "NA", c(-1:1), ] 

這就造成了這樣的錯誤:

Error in x[j] : only 0's may be mixed with negative subscripts 

我在做什麼錯?

回答

1

試試這個

keepindex <- which(!is.na(basisanddowngradessingledates[,2])) 
# keepindex <- which(basisanddowngradessingledates[,2] == "NA") # try this if "NA" instead of NA 
keepindex <- unique(c(keepindex-1, keepindex, keepindex+1)) 
basisanddowngradessingledates[keepindex,] 
+0

第二個工作,但我不得不改變你的==「NA」到!=,因爲我想降級的日期,而不是在沒有降級發生的人。否則很好,非常感謝。 – rbonac

+0

好的。忘了你想要'!=' – CPak