conditionally remove leading or trailing `.` character in R
Use regular expressions:
test <- c('.name.1.','name.2','.name.3.')
gsub('^\\.|\\.$', '', test)
# [1] "name.1" "name.2" "name.3"
The two backslashes, \\
, in the regular expression escape the dot, .
, which would actually mean any character. The caret, ^
, marks the beginning of the string, the dollar, $
, the end of the string. The pipe, |
, is a logical "or". So in essence the regular expression matches a dot at the beginning of the string or a dot at the end of the string and replaces it with an empty string.
More information on regular expressions can be found here and information on gsub and related functions here.
A quick function using the substr
function:
fun1 <- function(x) substr(x, 1 + (1 * as.numeric(substr(x,1,1)=='.')), nchar(x) - (1 * as.numeric(substr(x, nchar(x), nchar(x)) == '.')))
We use substr
to check for a .
in the first and last elements of the string, then we use substr
again to extract certain parts of the text. For example, if there is a .
in the first character, but not in the second, we'll extract: substr(text, 2, nchar(text))
.
fun1(test)
[1] "name.1" "name.2" "name.3"