MAC

时间:2016-05-17 16:47:22

标签: r macos encode

我试图下载文件并加载到R中,但它无法正常工作。 我使用R 3.1.3

在MAC上

该文件采用csv格式(并且可以选择json格式)。

这里是文件的网址(csv和json): http://dadosabertos.dataprev.gov.br/opendata/con02/formato=csv http://dadosabertos.dataprev.gov.br/opendata/con02/formato=json

我知道我可以下载文件,在本地文本编辑器中打开,保存为utf-8,然后导入到R.但我想要一个更自动化的解决方案,并不涉及使用另一个软件。而且,顺便说一句,即使这个解决方案也没有像我预期的那样简单。

这是我到目前为止所尝试的内容: 由于该文件是葡萄牙文,我知道它可能是utf-8。

library(jsonlite)
options(encoding = "utf-8")
url <- "http://dadosabertos.dataprev.gov.br/opendata/con02/formato=json"
prev <- fromJSON(url)

错误信息:

词法错误:UTF8字符串中的无效字节。           :[{&#34; node&#34;:{&#34; Ano&#34;:&#34; 1988&#34;,&#34;Esp�cie&#34;:&#34; 42-Ap Tempo Contribuio                      (就在这里)------ ^

我也试过了 url1&lt; - &#34; http://dadosabertos.dataprev.gov.br/opendata/con02/formato=csv&#34; prev&lt; - read.csv(url,sep =&#34;,&#34;)

但它也没有用。我也尝试使用:

Sys.setlocale("LC_ALL", 'en_US.UTF-8')

但它没有任何区别。

2 个答案:

答案 0 :(得分:1)

至少csv版本似乎是ISO-8859-1而不是UTF-8。您可以使用curl命令检查Content-Type,如下所示:

$ curl -I "http://dadosabertos.dataprev.gov.br/opendata/con02/formato=csv"
HTTP/1.1 200 OK
Set-Cookie: ACE_STICKY=R835601189; path=/; expires=Thu, 19-May-2016 00:43:56 GMT
Server: nginx/1.2.4
Date: Wed, 18 May 2016 00:27:45 GMT
Content-Type: text/plain; charset=ISO-8859-1
Connection: keep-alive
X-Powered-By: PHP/5.3.3
Content-Disposition: attachment; filename="CON02.csv";
Access-Control-Allow-Origin: *

从查看内容看,这似乎是正确的。我不熟悉r的编码选项,但尝试设置`options(encoding =&#34; ISO-8859-1&#34;),看看会发生什么。

答案 1 :(得分:1)

我通过这样做解决了它:

url<-"http://dadosabertos.dataprev.gov.br/opendata/act10/formato=json"
a<-readLines(file(url, encoding="ISO-8859-1"), warn=FALSE)
prev<-fromJSON(a)