【问题标题】:stringr str_locate_all not returning the proper index in a dplyr stringstringr str_locate_all 未在 dplyr 字符串中返回正确的索引
【发布时间】:2017-06-08 14:18:56
【问题描述】:

我正在尝试使用 str_locate_all 查找 dplyr 链中第三次出现“/”的索引,但它没有返回正确的索引。

  ga.categoryViews.2016 <- ga.data %>%
    mutate(province = str_sub(pagePath,2,3),
           index = str_locate_all(pagePath, '/')[[1]][,"start"][3],
           category = str_sub(pagePath, 
                              str_locate_all(pagePath, '/')[[1]][,"start"][3] + 1,
                              ifelse(str_detect(pagePath,'\\?'), str_locate(pagePath, '\\?') - 1, str_length(pagePath))
                              )
             )

它返回的一个例子是

第一列是pagePath,第四列是索引

它似乎总是返回 12 的索引。

感谢任何帮助。

谢谢,

【问题讨论】:

    标签: r dplyr stringr


    【解决方案1】:

    你需要使用rowwise(),即

    library(dplyr)
    library(stringr)
    
    df %>% 
     rowwise() %>% 
     mutate(new = str_locate_all(v1, '/')[[1]][,2][3])
    
    Source: local data frame [2 x 2]
    Groups: <by row>
    
    # A tibble: 2 x 2
    #                              v1   new
    #                           <chr> <int>
    #1 /on/srgsfsfs-gfdgdg/dfgsdfg-df    20
    #2        /on/sgsddg-dfgsd/dfg-dg    17
    

    数据

    x <- c('/on/srgsfsfs-gfdgdg/dfgsdfg-df', '/on/sgsddg-dfgsd/dfg-dg')
    df <- data.frame(v1 = x, stringsAsFactors = F)
    
    df
    #                              v1
    #1 /on/srgsfsfs-gfdgdg/dfgsdfg-df
    #2        /on/sgsddg-dfgsd/dfg-dg
    

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 2011-08-06
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多