gsub错误在R中将大写字母转换为小写字母
gsub error turning upper to lower case in R
我想重新编码一些标识符,从大写到小写。
我不确定这里的问题是什么。
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:]]"
有什么建议吗?
gsub
function takes a regular expression as the first argument, and a replacement string as a second one that cannot have special characters/classes that are used in a regular expression. They are rather treated as literals. Thus, you are trying to replace each uppercase letter with a literal string [[:lower:]]
(see my demo).
要将数据框的值变为小写,您必须使用 tolower()
(正如已经指出的那样):
n = c('AFD.434', 'BSD.23', 'F234.FF')
tolower(n)
见demo
输出:
[1] "afd.434" "bsd.23" "f234.ff"
请注意,当我们需要将字符串的特定部分大写时,Franks 关于使用 Perl \L
运算符的建议很方便,但在您的情况下,这似乎是不必要的开销。
您的 gsub 调用将每次出现都替换为文字字符串“[[:lower:]]”。
最简单的解决方案是不使用正则表达式;只需使用 tolower()
(如评论/其他答案中所述)。
正则表达式的一种可能方法是使用 Perl 扩展模式和 \L
修饰符转换为小写:
gsub(pattern = '([[:upper:]])', perl = TRUE, replacement = '\L\1', n)
这种方法
- 使用捕获组
(...)
来"remember"匹配
- 使用反向引用
</code> 来引用替换字符串中的匹配项</li>
<li>使用 <code>\L
修饰符将匹配项转换为小写
有关详细信息,请参阅 gsub
的联机帮助。
我想重新编码一些标识符,从大写到小写。
我不确定这里的问题是什么。
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:]]"
有什么建议吗?
gsub
function takes a regular expression as the first argument, and a replacement string as a second one that cannot have special characters/classes that are used in a regular expression. They are rather treated as literals. Thus, you are trying to replace each uppercase letter with a literal string [[:lower:]]
(see my demo).
要将数据框的值变为小写,您必须使用 tolower()
(正如已经指出的那样):
n = c('AFD.434', 'BSD.23', 'F234.FF')
tolower(n)
见demo
输出:
[1] "afd.434" "bsd.23" "f234.ff"
请注意,当我们需要将字符串的特定部分大写时,Franks 关于使用 Perl \L
运算符的建议很方便,但在您的情况下,这似乎是不必要的开销。
您的 gsub 调用将每次出现都替换为文字字符串“[[:lower:]]”。
最简单的解决方案是不使用正则表达式;只需使用 tolower()
(如评论/其他答案中所述)。
正则表达式的一种可能方法是使用 Perl 扩展模式和 \L
修饰符转换为小写:
gsub(pattern = '([[:upper:]])', perl = TRUE, replacement = '\L\1', n)
这种方法
- 使用捕获组
(...)
来"remember"匹配 - 使用反向引用
</code> 来引用替换字符串中的匹配项</li> <li>使用 <code>\L
修饰符将匹配项转换为小写
有关详细信息,请参阅 gsub
的联机帮助。