【问题标题】:Vectorized str_locate not working as intended矢量化 str_locate 未按预期工作
【发布时间】:2020-08-22 03:51:20
【问题描述】:

我有以下数据框:

df <- data.frame(string=c('abcde', 'cde'))

我想在每个字符串中找到“de”的end位置,我可以这样确定:

df %>% 
 rowwise() %>%
 mutate(pos=str_locate(string = string, pattern = "de")[2])

##   string    pos
##    abcde      5
##      cde      3

这是预期的输出但是我不想使用rowwise(),因为它对于大数据帧来说非常慢。

所以我尝试将我的函数矢量化并删除rowwise() 命令:

Vstr_locate <- Vectorize(str_locate)

df %>% 
 #rowwise() %>%
 mutate(pos=Vstr_locate(string = string, pattern = "de")[2])

但这没有用:

##   string    pos
##    abcde      5
##      cde      5

问题:

  • 为什么我的矢量化函数不起作用?
  • 如何在不使用rowwise() 的情况下获得预期的输出?

【问题讨论】:

    标签: r dplyr stringr


    【解决方案1】:

    括号内需要逗号

    df %>% 
      #rowwise() %>%
      mutate(pos=Vstr_locate(string = string, pattern = "de")[2,])
      string pos
    1  abcde   5
    2    cde   3
    

    查看两个函数的输出

    str_locate(string = "abcde", pattern = "de")
         start end
    [1,]     4   5
    

    对比

    Vstr_locate(string = "abcde", pattern = "de")
         abcde
    [1,]     4
    [2,]     5
    

    同样,如果你将每个应用到一个列表中

    library(purrr)
    strings <- c('abcde', 'cde')
    map(strings, str_locate, "de")
    [[1]]
         start end
    [1,]     4   5
    
    [[2]]
         start end
    [1,]     2   3
    

    对比

    map(strings, Vstr_locate, "de")
    [[1]]
         abcde
    [1,]     4
    [2,]     5
    
    [[2]]
         cde
    [1,]   2
    [2,]   3
    

    您想要的元素被索引为[2,]Vstr_locate

    【讨论】:

      【解决方案2】:

      str_locate 已经矢量化,不需要 rowwiseVectorize

      df %>% mutate(pos=str_locate(string = string, pattern = "de")[, 2])
      #   string pos
      # 1  abcde   5
      # 2    cde   3
      

      【讨论】:

        猜你喜欢
        • 2021-08-21
        • 2021-07-18
        • 1970-01-01
        • 2020-10-06
        • 1970-01-01
        • 1970-01-01
        • 2018-05-17
        • 1970-01-01
        • 2012-09-10
        相关资源
        最近更新 更多