【问题标题】:Using the grep command or another command for subsetting使用 grep 命令或其他命令进行子集化
【发布时间】:2021-02-07 17:42:03
【问题描述】:

我正在使用最近 5 年的 apple 和 google 使用 quant mode 命令

loadSymbols(c("AAPL", "GOOG"))
AAPL['2016::']

这是我拥有的数据集。

AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
2016-01-04   25.6525   26.3425  25.5000    26.3375   270597600      24.36454
2016-01-05   26.4375   26.4625  25.6025    25.6775   223164000      23.75398
2016-01-06   25.1400   25.5925  24.9675    25.1750   273829600      23.28912
2016-01-07   24.6700   25.0325  24.1075    24.1125   324377600      22.30621
2016-01-08   24.6375   24.7775  24.1900    24.2400   283192000      22.42415

它一直持续到 2020 年。我只想获取每个月第一天的 AAPL 交易量数据。所以一年会有12个数据,每个月的1号。我需要它 5 年。

使用以前的线程,我希望使用 grep 命令,但任何其他命令都会很有帮助。

【问题讨论】:

标签: r subset


【解决方案1】:

假设您的数据框名为df,这应该为您提供每月第一天的AAPL.Volume值:

df$AAPL.Volume[grepl("01$", df$AAPL.Open)]

【讨论】:

    【解决方案2】:

    我们可以使用 grep 和模式来匹配 4 位数字,后跟 -,然后是 2 位数字,- 和数据集 index 末尾的“01”来子集行

    out <- df[grep("^\\d{4}-\\d{2}-01", index(df)),]
    

    -输出

    head(out)
    #           AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
    #2016-02-01   24.1175   24.1775  23.8500    24.1075   163774000      22.30158
    #2016-03-01   24.4125   25.1925  24.3550    25.1325   201628400      23.37596
    #2016-04-01   27.1950   27.5000  27.0500    27.4975   103496000      25.57567
    #2016-06-01   24.7550   24.8850  24.5825    24.6150   116693200      23.03402
    #2016-07-01   23.8725   24.1175  23.8325    23.9725   104106000      22.43279
    #2016-08-01   26.1025   26.5375  26.1025    26.5125   152671600      24.80965
    

    数据

    df <- AAPL['2016::']
    

    【讨论】:

    • 谢谢,可惜没有。这就是我得到的 AAPL[grep("^\\d{4}-\\d{2}-01", rownames(AAPL)),] AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.调整
    • @ShaneMurphy 只需将其从 row.names 更改为 index
    【解决方案3】:

    使用grep 并查找"01" 的日期将返回那些有 -01 日期的月份的数据;如果数据有任何漏洞,则该月份将被跳过。如果不希望这样做,那么这里有一种方法可以获取每个年/月组的 第一 行:

    dat[!duplicated(gsub("-[0-9]{2}$", "", rownames(dat))),]
    #            AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
    # 2016-01-04   25.6525   26.3425     25.5    26.3375   270597600      24.36454
    

    tidyverse

    library(dplyr)
    # library(tibble)
    dat %>%
      tibble::rownames_to_column() %>%
      group_by(yearmon = gsub("-[0-9]{2}$", "", rowname)) %>%
      slice(1) %>%
      ungroup()
    # # A tibble: 1 x 8
    #   rowname    AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted yearmon
    #   <chr>          <dbl>     <dbl>    <dbl>      <dbl>       <int>         <dbl> <chr>  
    # 1 2016-01-04      25.7      26.3     25.5       26.3   270597600          24.4 2016-01
    

    【讨论】:

      猜你喜欢
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 2019-09-10
      • 2018-07-03
      • 1970-01-01
      • 2010-11-14
      • 2014-11-02
      相关资源
      最近更新 更多