I would like to recode some identifiers, from upper case to lower case.
I am not sure what the issue is here.
n = c('AFD.434', 'BSD.23', 'F234.FF')
gsub(pattern = '[[:upper:]]', replacement = '[[:lower:]]', n)
[1] "[[:lower:]][[:lower:]][[:lower:]].434" "[[:lower:]][[:lower:]][[:lower:]].23" "[[:lower:]]234.[[:lower:]][[:lower:]]"
Any advice?
How to Convert String to Lowercase in R 1 Convert Uppercase String to Lowercase in R. To convert an uppercase string to a lowercase string in R, use the tolower () method. ... 2 casefold () Function in R. The casefold () function in R is a generalized solution to convert to either lowercase or uppercase letters. 3 Conclusion. ...
The basic syntax of gsub in r:. gsub (search_term, replacement_term, string_searched, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE) The search term – can be a text fragment or a regular expression.
If we want to convert some characters to lower and others to upper case, we can apply the chartr function: The chartr function allows the specification of an old character pattern as well as of a new character pattern. The new pattern then replaces the old pattern.
Our characters are transformed to lower case if we specify upper = FALSE (default option) within the casefold function… In practice, the casefold function is not different compared to tolower and toupper. However, some R users prefer to use it, since it provides a better compatibility with S-PLUS.
Your gsub call replaces each occurrence with the literal string "[[:lower:]]".
The simplest solution is to not use regular expressions; simply use tolower()
(as already mentioned in the comments / other answers).
One possible approach with regular expressions is the usage of Perl extended mode and the \L
modifier to convert to lowercase:
gsub(pattern = '([[:upper:]])', perl = TRUE, replacement = '\\L\\1', n)
This approach
(...)
to "remember" the match\1
to refer to the match in the replacement string\L
modifier to convert the match to lowercaseSee the online help for gsub
for further details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With