Skip to contents

sub_string() can extract parts of a character from the left side, right side or from the middle. It is also able to start or end at specific letter sequences instead of positions.

Usage

sub_string(
  data_frame,
  variable,
  from = NULL,
  to = NULL,
  case_sensitive = TRUE,
  include_from = TRUE,
  include_to = TRUE,
  search_from_end = FALSE
)

Arguments

data_frame

A data frame which contains the variables to concatenate.

variable

A character variable to extract parts from.

from

A single character expression or a numeric vector of start positions.

to

A single character expression or a numeric vector of end positions.

case_sensitive

TRUE by default. When a character expression is passed as from or to it makes a difference whether a letter is written in upper or lower case. Pass FALSE to handle upper and lower case equally.

include_from

TRUE by default. Only applies when a character is passed as from. If TRUE the matched word is included in the substring, otherwise the substring starts after it.

include_to

TRUE by default. Only applies when a character is passed as to. If TRUE the whole matched word is included in the substring, otherwise the last place is removed.

search_from_end

FALSE by default. If TRUE the last occurrence of a character expression passed as from or to is looked up instead of the first one.

Value

Returns parts of a character vector.

See also

Other character manipulating functions: concat(), remove_blanks()

Examples

# Example data frame
my_data <- dummy_data(100)

# Extract text from the left
my_data[["left"]] <- my_data |> sub_string(education, to = 2)

# Extract text from the right
my_data[["right"]] <- my_data |> sub_string(education, from = 2)

# Extract text from the middle
my_data[["middle"]] <- my_data |> sub_string(education, from = 2, to = 3)

# Find text and extract from the left
my_data[["left2"]] <- my_data |> sub_string(education, to = "l")

# Find text and extract from the right
my_data[["right2"]] <- my_data |> sub_string(education, from = "l")

# Find text and extract from the middle
my_data[["middle2"]] <- my_data |> sub_string(education, from = "i", to = "l")