I want to store the first character of a string in a variable, and the rest of the string in another variable. For example:
x <- "foo"
prefix <- substr(x, 1, 1)
suffix <- substring(x, 2)
However, it seems a bit wasteful to call substr
and substring
. Isn't there a way to extract both the substring, and the remainder of the string (the "difference" between the substring and the original string) at once?
Maybe something like this:
substring(x, c(1, 2), c(1, nchar(x)))
# [1] "f" "oo"
Here is an idea using regex,
strsplit(gsub('^([A-z]{1})([A-z]+)$', '\\1_\\2', x), '_')
#[[1]]
#[1] "f" "oo"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With