Strings
Format numbers¶
sprintf("%02.1f%%", your_number) # (1)
# Output: "xxxx.x%"
sprintf("Pi to 3 decimal places: %.3f", pi)
# Output: "Pi to 3 decimal places: 3.142"
sprintf("Scientific notation of Pi: %e", pi) # (2)
# Output: "Scientific notation of Pi: 3.141593e+00"
sprintf("%s is %d years old", "Alice", 25) # (3)
# Output: "Alice is 25 years old"
-
- %%: Literal %
- %f: Double precision value in fixed-point notation
- %e, %E: Double precision value in exponential notation
-
- %d, %i: Integer value
- %s: Character string
Regular expression¶
Extract anything between certain words
stringr::str_extract_all(
string = .x,
pattern = "(?<=using last ).+(?= days)" # between the word 'using last ' and ' days'
)
- matching a dash followed by zero or more characters that are not a dash till the end ($) of the string and replace it with blank ('')
Replace¶
# Replace multiple strings at a time
rep_str = c('St'='Street','Blvd'='Boulevard','Pkwy'='Parkway')
df$address <- str_replace_all(df$address, rep_str)
String pad¶
Pad a string to a fixed width.