在R中,使用gsub删除除句点以外的所有标点符号 [英] in R, use gsub to remove all punctuation except period
问题描述
我是R的新手,希望您能帮助我.
I am new to R so I hope you can help me.
我想使用gsub删除除点号和减号外的所有标点符号,以便可以在数据中保留小数点和负号.
I want to use gsub to remove all punctuation except for periods and minus signs so I can keep decimal points and negative symbols in my data.
示例
我的数据框z具有以下数据:
My data frame z has the following data:
[,1] [,2]
[1,] "1" "6"
[2,] "2@" "7.235"
[3,] "3" "8"
[4,] "4" "$9"
[5,] "£5" "-10"
我想使用gsub("[[:punct:]]", "", z)
删除标点符号.
I want to use gsub("[[:punct:]]", "", z)
to remove the punctuation.
当前输出
> gsub("[[:punct:]]", "", z)
[,1] [,2]
[1,] "1" "6"
[2,] "2" "7235"
[3,] "3" "8"
[4,] "4" "9"
[5,] "5" "10"
但是,我想保留-"符号和."符号.签名.
I would like, however, to keep the "-" sign and the "." sign.
所需的输出
PSEUDO CODE:
> gsub("[[:punct:]]", "", z, except(".", "-") )
[,1] [,2]
[1,] "1" "6"
[2,] "2" "7.235"
[3,] "3" "8"
[4,] "4" "9"
[5,] "5" "-10"
有什么想法可以使某些字符免于gsub()函数吗?
Any ideas how I can make some characters exempt from the gsub() function?
推荐答案
您可以放回一些类似的匹配项:
You can put back some matches like this:
sub("([.-])|[[:punct:]]", "\\1", as.matrix(z))
X..1. X..2.
[1,] "1" "6"
[2,] "2" "7.235"
[3,] "3" "8"
[4,] "4" "9"
[5,] "5" "-10"
在这里,我保留.
和-
.
我想,下一步是将您的结果强制为数字矩阵,因此在这里,我将两个步骤结合起来:
And I guess , the next step is to coerce you result to a numeric matrix, SO here I combine the 2 steps like this:
matrix(as.numeric(sub("([.-])|[[:punct:]]", "\\1", as.matrix(z))),ncol=2)
[,1] [,2]
[1,] 1 6.000
[2,] 2 7.235
[3,] 3 8.000
[4,] 4 9.000
[5,] 5 -10.000
这篇关于在R中,使用gsub删除除句点以外的所有标点符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!