Skip to contents

Survey Tools - Split String and Extract by Positions

Usage

srv_extract_split(x, sep = " - ", position = 2, collapse = "_")

Arguments

x

character vector, each element of which is to be split. Other inputs, including a factor, will give an error.

sep

string to split by

position

positions to extract after split

collapse

character string to put between extracted pieces

Examples

x1 <- c(
  "Demographics - 1 - What is your age?",
  "Demographics - 2 - Where do you live?",
  "Politics - 1 - How do you describe yourself as?"
)

srv_extract_split(x1, position = c(1:3), collapse = ": ")
#> [1] "Demographics: 1: What is your age?"           
#> [2] "Demographics: 2: Where do you live?"          
#> [3] "Politics: 1: How do you describe yourself as?"
srv_extract_split(x1, position = c(3))
#> [1] "What is your age?"                "Where do you live?"              
#> [3] "How do you describe yourself as?"
srv_extract_split(x1, position = 1:2)
#> [1] "Demographics_1" "Demographics_2" "Politics_1"    

x2 <- c(
  "1: What sports do you like playing the most - select all that apply",
  "2: What sports do you like watching the most - select all that apply"
)

library(dplyr)
x2 %>%
  srv_extract_split(sep = ": ", position = 2) %>%
  srv_extract_split(sep = " - ", position = 1)
#> [1] "What sports do you like playing the most" 
#> [2] "What sports do you like watching the most"