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"
Если вы 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"
(или вы также можете заменить на ""
.)
В 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 ~
Данные:
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")