【发布时间】:2017-05-02 09:19:41
【问题描述】:
This question 似乎可以轻松删除 R 中字符串中的空格字符。但是当我加载下表时,我无法删除两个数字之间的空格(例如11 846.4):
require(XML)
require(RCurl)
require(data.table)
link2fetch = 'https://www.destatis.de/DE/Themen/Branchen-Unternehmen/Landwirtschaft-Forstwirtschaft-Fischerei/Feldfruechte-Gruenland/Tabellen/ackerland-hauptnutzungsarten-kulturarten.html'
theurl = getURL(link2fetch, .opts = list(ssl.verifypeer = FALSE) ) # important!
area_cult10 = readHTMLTable(theurl, stringsAsFactors = FALSE)
area_cult10 = rbindlist(area_cult10)
test = sub(',', '.', area_cult10$V5) # change , to .
test = gsub('(.+)\\s([A-Z]{1})*', '\\1', test) # remove LETTERS
gsub('\\s', '', test[1]) # remove white space?
为什么我不能删除test[1] 中的空格?
感谢您的任何建议!这可能不是空格字符吗?也许答案真的很简单,我忽略了一些东西。
【问题讨论】:
-
好的,在编织了一个 html 之后,我发现它不是一个空格,而是一个非制动空格。在 html 中看起来像
 ,可以使用\u00A0进行搜索。棘手! -
我已经尝试了你的代码并得到了
[1] "11846.4"- 那里没有空格。 -
奇怪。重新启动 R 并运行代码后,我仍然得到这个空间
[1] "11 846.4"。但是我可以用上面提到的\u00A0删除它。也许不同的软件包版本? -
你知道,我刚运行你的代码时它就被删除了。当我开始检查是否可以改进正则表达式时,它停止删除空间。我确认:如您所示创建
test,空白消失。如果我使用test1 <- gsub("[\\sA-Za-z]+", "", area_cult10$V5)删除所有空格和字母,则空格仍然存在。gsub("[[:space:]A-Za-z]+", "", area_cult10$V5)有效。 -
试试
sub(",", ".", gsub("[[:space:]A-Za-z]+|\\W+$", "", area_cult10$V5), fixed=TRUE)