stringr str_locate_all 没有在 dplyr 字符串中返回正确的索引
stringr str_locate_all not returning the proper index in a dplyr string
我正在尝试使用 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,第四列是index
它似乎总是返回 12 的索引。
感谢任何帮助。
谢谢,
您需要使用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
我正在尝试使用 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,第四列是index
它似乎总是返回 12 的索引。
感谢任何帮助。
谢谢,
您需要使用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