str_split_alt: Split a string of text by a specified pattern and return a...

View source: R/str_split_alt.R

str_split_altR Documentation

Split a string of text by a specified pattern and return a vector of the split text

Description

This function works similarly to stringr::str_split except that it returns a vector rather than a list of vectors. Also, you can have it return only one item in that vector instead of the entire vector, which works better when you're trying to extract a specified piece of text and fill it into a column of a data.frame or tibble.

Usage

str_split_alt(string, pattern, i = NA, retainPattern = FALSE)

Arguments

string

The string of text to be split into pieces

pattern

The pattern to use for splitting the text. The pattern will not be retained in the output unless retainPattern = TRUE.

i

The index of the output vector to be returned. If left as NA, this will return all items in the vector. If set to a specific number i, it will return only the ith item of that vector. If set to "last", it will return only the last item of the vector.

retainPattern

TRUE or FALSE for whether to retain the pattern that was used to separate the input text in the output vector. Warning: This was set up for a situation in which the user is only looking to match a single, exact pattern and not a pattern with regular expressions in it. The function will still work if you use regex, but the output won't be what you're likely expecting.

Value

Returns a vector

Examples


# Applied to a vector of length 1:
MyString <- c("First filename.xlsx Second filename.xlsx")
str_split_alt(MyString, ".xlsx")
str_split_alt(MyString, ".xlsx", i = 1)
str_split_alt(MyString, ".xlsx", i = "last")
str_split_alt(MyString, ".xlsx", retainPattern = TRUE)

# Applied to a longer vector, e.g., a column in a data.frame:
MyDF <- data.frame(ColA = paste("Item", 1:4),
                   ColB = c("This is a string to be split.",
                            "This one, too",
                            "Also split this",
                            "Last, split this one."),
                  ColC = c(str_c(paste0("MyFile", 1:3, ".xlsx"), collapse = " "),
                            str_c(paste0("MyFile", 1:5, ".xlsx"), collapse = " "),
                            str_c(paste0("MyFile", 1:10, ".xlsx"), collapse = " "),
                            str_c(paste0("MyFile", 1:2, ".xlsx"), collapse = " ")))

MyDF$ColD <- str_split_alt(MyDF$ColB, " ", "last")
MyDF$ColE <- str_split_alt(MyDF$ColB, " ", i = 1)
MyDF$ColF <- str_split_alt(MyDF$ColC, " ", i = 4, retainPattern = TRUE)



shirewoman2/LaurasHelpers documentation built on Oct. 22, 2023, 2:07 p.m.