2016-05-17 71 views
0

我试图下载一个文件并加载到R,但它不工作。 我在MAC上,使用R 3.1.3MAC上的编码问题

该文件是csv格式(并且有一个json格式选项)。

下面是该文件的URL(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字符串无效字节。 :[{“node”:{“Ano”:“1988”,“Esp cie”:“42-Ap TempoContribui o (right here)------^

我也试图 URL1 < - “http://dadosabertos.dataprev.gov.br/opendata/con02/formato=csv” 上一个< - read.csv(URL,月= “”)

但它也没有工作,我也尝试过使用方法:

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

但它没有任何区别。

回答

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 =“ISO-8859-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)