从字符串中删除所有字符除外

时间:2011-02-08 00:54:18

标签: regex r gdata

我想从字符串中删除所有不是数字,减号或小数点的字符。

我使用read.xls从Excel导入数据,其中包含一些奇怪的字符。我需要将它们转换为数字。我对正则表达式不太熟悉,因此需要一种更简单的方法来执行以下操作:

excel_coords <- c(" 19.53380Ý°", " 20.02591°", "-155.91059°", "-155.8154°")
unwanted <- unique(unlist(strsplit(gsub("[0-9]|\\.|-", "", excel_coords), "")))
clean_coords <- gsub(do.call("paste", args = c(as.list(unwanted), sep="|")), 
                     replacement = "", x = excel_coords)

> clean_coords
[1] "19.53380"   "20.02591"   "-155.91059" "-155.8154" 

如果有人可以告诉我为什么这些字符出现在我的一些数据中(学位符号是原始Excel工作表的一部分,但其他人不是),可以获得奖励。

3 个答案:

答案 0 :(得分:5)

短而甜蜜。感谢G. Grothendieck的评论。

gsub("[^-.0-9]", "", excel_coords)

来自http://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html:&#34;字符类是[和]之间的字符列表,它匹配该列表中的任何单个字符;除非列表的第一个字符是插入符号^,否则它匹配列表中没有的任何字符。&#34;

答案 1 :(得分:2)

也可以使用strsplitsapplypaste以及索引正确的字符而不是错误的字符来完成:

 excel_coords <- c(" 19.53380Ý°", " 20.02591°", "-155.91059°", "-155.8154°")
 correct_chars <- c(0:9,"-",".")
 sapply(strsplit(excel_coords,""), 
          function(x)paste(x[x%in%correct_chars],collapse=""))

[1] "19.53380"   "20.02591"   "-155.91059" "-155.8154" 

答案 2 :(得分:1)

gsub("(.+)([[:digit:]]+\\.[[:digit:]]+)(.+)", "\\2", excel_coords)
[1] "9.53380" "0.02591" "5.91059" "5.8154" 
相关问题