View source: R/str_split_alt.R
str_split_alt | R Documentation |
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.
str_split_alt(string, pattern, i = NA, retainPattern = FALSE)
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 |
i |
The index of the output vector to be returned. If left as |
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. |
Returns a vector
# 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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.