我想从字符串中删除所有不是数字,减号或小数点的字符.
我使用Excel导入数据read.xls,其中包括一些奇怪的字符.我需要将它们转换为数字.我对正则表达式不太熟悉,所以需要一种更简单的方法来执行以下操作:
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"
Run Code Online (Sandbox Code Playgroud)
奖金如果有人能告诉我为什么这些字符出现在我的一些数据中(学位标志是原始Excel工作表的一部分,但其他人不是).
简短又甜蜜.感谢G. Grothendieck的评论.
gsub("[^-.0-9]", "", excel_coords)
Run Code Online (Sandbox Code Playgroud)
来自http://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html :"字符类是[和]之间的字符列表,它匹配任何单个字符list;除非列表的第一个字符是插入符号^,否则它匹配列表中没有的任何字符."