gsub error turning upper to lower case in R

后端 未结 2 1258
时光说笑
时光说笑 2021-01-12 18:18

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         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 19:07

    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.

提交回复
热议问题