【问题标题】:Accessing results of gregexpr访问 gregexpr 的结果
【发布时间】:2018-08-16 10:55:02
【问题描述】:

我想使用 gregexpr 函数来查找字符串中子字符串的开始和结束位置。该函数在控制台中运行良好,但我无法访问起始位置或字符串长度的结果:

g <- gregexpr("e", "cheese")

g

[[1]]
[1] 3 4 6
attr(,"match.length")
[1] 1 1 1
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE

g[[1]][1] 仅显示第一个值 (3),但我需要创建一个包含所有起始位置和长度值的向量。谢谢。

【问题讨论】:

  • 您只得到第一个列表元素的第一个元素。这样做:g[[1]]
  • 这只是调出了g的全部内容。我需要能够访问单个元素,例如3、4、6。

标签: r


【解决方案1】:

你可以这样提取它们:

g <- gregexpr("e", "cheese")

# one liner for : starts <- g[[1]]
#                 attributes(starts) <- NULL
starts <- `attributes<-`(g[[1]],NULL) 

lens <- attr(g[[1]],'match.length')

> starts
[1] 3 4 6
> lens
[1] 1 1 1

当然,这仅适用于文本长度为 1 的情况(如示例中所示,因为它仅包含 "cheese")。否则,您需要使用 g[[2]]g[[3]] ... 等迭代 g 的元素。

【讨论】:

    【解决方案2】:

    您可以使用 unlist,您将收到职位列表。一旦需要只有第一个和最后一个,可以使用最小值和最大值

    unlist(g)
    

    [1] 3 4 6

    【讨论】:

    • 布里尔。很简单。
    【解决方案3】:

    另一种方法是:

    g <- gregexpr("e", "cheese")
    
    g[[1]][1:length(g[[1]])]
    #[1] 3 4 6
    

    以及使用unlist 方法的微基准测试:

    microbenchmark::microbenchmark(
       g[[1]][1:length(g[[1]])], 
       unlist(g)
    )
    
    #Unit: nanoseconds
    #                     expr min  lq   mean median  uq   max neval
    # g[[1]][1:length(g[[1]])] 378 378 653.80    379 756  8307   100
    #                unlist(g)   0 378 544.32    378 378 15104   100
    

    【讨论】:

      猜你喜欢
      • 2017-04-17
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      相关资源
      最近更新 更多