Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a substring from a string, as well as the remainder of the string

Tags:

string

r

substr

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?

like image 627
DeltaIV Avatar asked Dec 01 '22 11:12

DeltaIV


2 Answers

Maybe something like this:

substring(x, c(1, 2), c(1, nchar(x)))
# [1] "f"  "oo"
like image 134
timfaber Avatar answered Dec 05 '22 04:12

timfaber


Here is an idea using regex,

strsplit(gsub('^([A-z]{1})([A-z]+)$', '\\1_\\2', x), '_')
#[[1]]
#[1] "f"  "oo"
like image 23
Sotos Avatar answered Dec 05 '22 05:12

Sotos