Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gsub error turning upper to lower case in R

Tags:

regex

r

gsub

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?

like image 773
giac Avatar asked Jun 05 '15 10:06

giac


People also ask

How to convert uppercase to lowercase in R?

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. ...

What is the syntax of GSUB in R?

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.

How to convert some characters to lower and others to upper case?

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.

How to transform characters in casefold to lower case in R?

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.


Video Answer


1 Answers

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

  • uses a capturing group (...) to "remember" the match
  • uses a backreference \1 to refer to the match in the replacement string
  • uses the \L modifier to convert the match to lowercase

See the online help for gsub for further details.

like image 52
Frank Schmitt Avatar answered Sep 18 '22 00:09

Frank Schmitt