I have a character variable that I would like to split into 2 variables based on a \"-\" delimiter, however, I would only like to split based on the last delimiter as there
A solution based on stringi
and data.table
: reverse the string and split it into fixed items and then reverse back:
library(stringi)
x <- c('foo - bar', 'hey-now-man', 'say-now-girl', 'fine-now')
lapply(stri_split_regex(stri_reverse(x), pattern = '[-\\s]+', n = 2), stri_reverse)
If we want to make a data.frame
with this:
y <- lapply(stri_split_regex(stri_reverse(x), pattern = '[-\\s]+', n = 2), stri_reverse)
y <- setNames(data.table::transpose(y)[2:1], c('output1', 'output2'))
df <- as.data.frame(c(list(input = x), y))
# > df
# input output1 output2
# 1 foo - bar foo bar
# 2 hey-now-man hey-now man
# 3 say-now-girl say-now girl
# 4 fine-now fine now