【问题标题】:Find the line of the match character找到匹配字符的行
【发布时间】:2021-04-21 06:39:14
【问题描述】:

我想查看字符所在的行。

预期的答案是包含字符 BTC 的 4 行数字。

library(stringr)
library(quantmod)  
symbols <- stockSymbols()
symbols <- symbols[,1]
    u <- symbols 
    a <- "BTC"
    
    str_detect(a, u)
    table(str_detect(a, u))

【问题讨论】:

    标签: r dplyr tidyverse tidyr data-manipulation


    【解决方案1】:

    您可以使用grep 获取模式a 出现的索引。

    #Index
    grep(a, u)
    #[1] 3437
    
    #Value
    grep(a, u, value = TRUE)
    #[1] "EBTC"
    

    使用stringr

    library(stringr)
    
    #Index
    str_which(u, a)
    
    #Value
    str_subset(u, a)
    

    【讨论】:

      【解决方案2】:

      您可以使用 tidyverse 方式,使用 filter() 函数:

      filter(dataset, column == "BTC")
      

      或者使用基础 R 中的 grep() 函数:

      grep("BTC", dataset$column)
      

      这将为您提供您正在寻找的内容的索引(位置)

      【讨论】:

        【解决方案3】:

        我们可以使用greplwhich

        which(grepl(a, u))
        

        【讨论】:

          【解决方案4】:

          另一个基本 R 选项可能是 which + regexpr(但我认为 grepgrepl 显然更有效和直接)

          which(regexpr(a, u)>0)
          

          【讨论】:

            猜你喜欢
            • 2013-05-21
            • 2015-10-19
            • 2017-04-08
            • 2014-02-11
            • 1970-01-01
            • 2013-02-25
            • 2014-05-08
            • 2014-09-21
            • 1970-01-01
            相关资源
            最近更新 更多