Extract the substring from the string as well as the rest of the string

I want to store the first character of a string in a variable and the rest of the string in another variable. For instance:

x <- "foo"
prefix <- substr(x, 1, 1)
suffix <- substring(x, 2)

However, it seems wasteful to call substrand substring. Is there no way to extract both the substring and the rest of the string (the "difference" between the substring and the source string)?

+4
source share
4 answers

Maybe something like this:

substring(x, c(1, 2), c(1, nchar(x)))
# [1] "f"  "oo"
+10
source

Here is an idea using regex,

strsplit(gsub('^([A-z]{1})([A-z]+)$', '\\1_\\2', x), '_')
#[[1]]
#[1] "f"  "oo"
+2
source

str_split stringr:

require(stringr)
x<-c("foo", "hello", "world")
str_split(x,"(?<=.{1})",2)
#[[1]]
#[1] "f"  "oo"
#[[2]]
#[1] "h"    "ello"
#[[3]]
#[1] "w"    "orld"
+1

separate tidyr

library(tidyr)
separate(data_frame(x), x, into = c('prefix', 'suffix'), sep=1)
# A tibble: 3 × 2
#  prefix suffix 
#* <chr> <chr>
#1     f    oo
#2     h  ello
#3     w  orld

x<-c("foo", "hello", "world")
+1

Source: https://habr.com/ru/post/1675349/


All Articles