用`gsub`替换点 [英] Replace dots using `gsub`
问题描述
我正在尝试替换所有的."在数据框的特定列中使用"/".每个单元格中还有其他字符,我想确保只更改.". 当我使用gsub时,我得到的输出似乎可以进行更改,但是当我转到View()时,实际上并没有进行更改...我认为gsub应该实际上是在更改数据帧中的值.我使用不正确吗?我下面有我的代码.
I am trying to replace all the "." in a specific column of my data frame with "/". There are other characters in each cell and I want to make sure I only change the "."'s. When I use gsub, I get an output that appears to make the changes, but then when I go to View(), the changes are not actually made...I thought gsub was supposed to actually change the value in the data frame. Am I using it incorrectly? I have my code below.
gsub(".", "/", spy$Identifier, ignore.case = FALSE, perl = FALSE,
fixed = TRUE, useBytes = FALSE)
我也尝试了sub,但是下面的代码将每个条目本身更改为"/",我不确定如何更改它.
I also tried sub, but the code I have below changed every entry itself to "/" and I am not sure how to change it.
spy$Identifier <- sub("^(.).*", "/", spy$Identifier)
谢谢!
推荐答案
我的建议是转义".字符:
My recommendation would be to escape the "." character:
spy$Identifier <- gsub("\\.", "/", spy$Identifier)
在正则表达式中,句点是与任何字符匹配的特殊字符. 转义"它告诉搜索寻找实际时期.在R的gsub中,这是通过两个反斜杠(即:"\\")完成的.在其他语言中,它通常只是一个反斜杠.
In regular expression, a period is a special character that matches any character. "Escaping" it tells the search to look for an actual period. In R's gsub this is accomplished with two backslashes (i.e.: "\\"). In other languages, it's often just one backslash.
这篇关于用`gsub`替换点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!