String Functions
Hauke Sonnenberg
2024-03-18
Source:vignettes/functions_string.Rmd
functions_string.Rmd
The following functions are returning or analysing strings.
Function appendSuffix()
This function adds a suffix to all elements of a vector of character.
It is mainly a shortcut to paste0(values, suffix)
but
allows to define values to be omitted:
# Define a vector of character
values <- c("id", letters[1:5])
# Add a suffix to all elements except "id"
kwb.utils::appendSuffix(values, "_value", valuesToOmit = "id")
#> [1] "id" "a_value" "b_value" "c_value" "d_value" "e_value"
Function collapsed()
The function call collapsed(x, sep)
is a shortcut to
paste(x, collapse = sep)
. It allows for shorter code and
improved readability.
Function commaCollapsed()
The function call commaCollapsed(x)
is a shortcut to
paste(x, collapse = ",")
. It allows for shorter code and
improved readability.
kwb.utils::commaCollapsed(1:10)
#> [1] "1,2,3,4,5,6,7,8,9,10"
kwb.utils::commaCollapsed(letters)
#> [1] "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"
Function defaultLevels()
When given a vector of character, this function returns the sorted
unique values of the input vector. When given a vector of numeric with
all differences being a multiple of the step
argument
(defaulting to 1
), the step
-incremented
sequence of values between the smallest and the highest value is
returned.
# Vector of character -> The sorted unique values are returned
kwb.utils::defaultLevels(c("melon", "apple", "melon", "pear", "apple"))
#> [1] "apple" "melon" "pear"
# The differences between the values are not all a multiple of the step
# -> Return sorted unique values
kwb.utils::defaultLevels(c(5, 8, 1), step = 2)
#> [1] 1 5 8
# The differences between the values are all a multiple of the step
# -> Return step-incremented sequence between min and max
kwb.utils::defaultLevels(c(1.5, 4.5, 10.5), step = 1.5)
#> [1] 1.5 3.0 4.5 6.0 7.5 9.0 10.5
Function stringStartsWith()
Returns TRUE
for character strings starting with a given
prefix. Since R version 3.3.0 there is a function
startsWith()
in base R so that there is no need to use my
function any more. What a pity.