regmatches(vec, gregexpr("(?<=--!!).*", vec, perl = TRUE))
# [[1]]
# character(0)
# [[2]]
# [1] "Less than $10,000"
# [[3]]
# [1] "Less than $10,000!!With cash rent"
# [[4]]
# [1] "Less than $10,000!!With cash rent!!Less than $100"
If you unlist
从这里开始,您会注意到您“丢失”了第一个条目,不确定这是否是一个问题。
unlist(regmatches(vec, gregexpr("(?<=--!!).*", vec, perl = TRUE)))
# [1] "Less than $10,000"
# [2] "Less than $10,000!!With cash rent"
# [3] "Less than $10,000!!With cash rent!!Less than $100"
如果这是一个问题,那么
vecout <- regmatches(vec, gregexpr("(?<=--!!).*", vec, perl = TRUE))
unlist(replace(vecout, lengths(vecout) < 1, NA))
# [1] NA
# [2] "Less than $10,000"
# [3] "Less than $10,000!!With cash rent"
# [4] "Less than $10,000!!With cash rent!!Less than $100"
(或者你可以替换为""
以及。)
In a dplyr
管道:
tibble(vec = c("Estimate!!Total",
# "Estimate!!Total!!Household income in the past 12 months (in 2018 inflation-adjusted dollars) --!!Less than $10,000",
# "Estimate!!Total!!Household income in the past 12 months (in 2018 inflation-adjusted dollars) --!!Less than $10,000!!With cash rent",
# "Estimate!!Total!!Household income in the past 12 months (in 2018 inflation-adjusted dollars) --!!Less than $10,000!!With cash rent!!Less than $100")) %>%
mutate(out = regmatches(vec, gregexpr("(?<=--!!).*", vec, perl = TRUE)), out = replace(out, lengths(vecout) < 1, NA), out = unlist(out))
+ + # A tibble: 4 x 2
# vec out
# <chr> <chr>
# 1 Estimate!!Total <NA>
# 2 Estimate!!Total!!Household income in the past ~ Less than $10,000
# 3 Estimate!!Total!!Household income in the past ~ Less than $10,000!!With cash ~
# 4 Estimate!!Total!!Household income in the past ~ Less than $10,000!!With cash ~
Data:
vec <- c("Estimate!!Total",
"Estimate!!Total!!Household income in the past 12 months (in 2018 inflation-adjusted dollars) --!!Less than $10,000",
"Estimate!!Total!!Household income in the past 12 months (in 2018 inflation-adjusted dollars) --!!Less than $10,000!!With cash rent",
"Estimate!!Total!!Household income in the past 12 months (in 2018 inflation-adjusted dollars) --!!Less than $10,000!!With cash rent!!Less than $100")