Pasting Strings Together

library(stringr)

hello <- "Hello"

comma <- ","

world <- "World"

 
# Base R

paste(hello, comma, world, "!", sep = "")
## [1] "Hello,World!"
paste0(hello, comma, " ",world, "!")
## [1] "Hello, World!"
# stringr 

str_c(hello, comma, " ",world, "!")
## [1] "Hello, World!"

String Length

string1 <- "This is a string!"

str_length(string1)
## [1] 17

Substring

degrees <- c("BS Economics", "BA English")

str_sub(degrees, 1, 2)
## [1] "BS" "BA"

String Matching

major <- "000133 - Biology"

str_match(major, "[0-9]+")
##      [,1]    
## [1,] "000133"
str_match(major, "[:punct:]")
##      [,1]
## [1,] "-"
str_match(major, "[a-zA-Z]+")
##      [,1]     
## [1,] "Biology"

String Detection

fields_of_study <- c("Economics", "Biology", "Sociology", "Mathematics")

str_detect(fields_of_study, "ics")
## [1]  TRUE FALSE FALSE  TRUE
fields_of_study[str_detect(fields_of_study, "ics") == TRUE]
## [1] "Economics"   "Mathematics"

Change Case of Letters

str_to_upper("computer science")
## [1] "COMPUTER SCIENCE"
str_to_lower("STATISTICS")
## [1] "statistics"