【问题标题】:Select multiple rows by condition in R在R中按条件选择多行
【发布时间】:2017-10-11 13:34:40
【问题描述】:

我的数据集有以下摘录:

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”的行中,表示发生了降级。在我上面的示例中,行 [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

我做错了什么?

【问题讨论】:

    标签: r select intervals tidyverse


    【解决方案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,]
    

    【讨论】:

    • 第二个有效,但我必须将您的 == "NA" 更改为 !=,因为我想要降级日期,而不是没有降级发生的日期。否则非常好,非常感谢。
    • 好收获。忘了你想要!=
    猜你喜欢
    • 2021-11-29
    • 1970-01-01
    • 2021-09-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2020-10-01
    • 1970-01-01
    相关资源
    最近更新 更多