上传CSV以R中的API [英] Uploading a csv to an api in R

查看:149
本文介绍了上传CSV以R中的API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使我使用的技巧从的 http://geocoding.geo.census.gov/geo$c$cr/Geoc​​oding_Services_API.pdf 相对=nofollow。他们给了调用API,用于批处理的shell命令是

To make calls to the census geocoder api I am using tips from the documentation found at http://geocoding.geo.census.gov/geocoder/Geocoding_Services_API.pdf under the heading "Batch Geocoding". The shell command they give for calling the api for a batch is

curl --form addressFile=@address.csv --form benchmark=4 http://geocoding.geo.census.gov/geocoder/locations/addressbatch --output geocoderesult.csv

,其中address.csv是要上载的文件。

where address.csv is the file to be uploaded.

这完美的作品。不过,我想创造的R脚本来使整个过程自动化。

This works perfectly. However, I would like to create an R script to make the whole process automated.

什么是做R中的上述命令等价的方式?可以postForm()在RCurl包做到这一点?

What would be an equivalent way to do the above command in R? Could postForm() in the RCurl package accomplish this?

结果

BTW,CSV文件的每一行得到上传(address.csv)必须是形式

BTW, each line of the csv file getting uploaded ("address.csv") must be of the form

Unique ID, Street address, City, State, ZIP

因此​​,例如,它可能只包含苹果和Facebook地址像

So, for example, it could just contain addresses for Apple and Facebook like

1, 1 Infinite Loop, Cupertino, CA, 95014
2, 1 Hacker Way, Menlo Park, CA, 94025

谢谢!

推荐答案

使用 HTTR 库,直接翻译过来是

Using the httr library, a direct translation would be

library('httr')

apiurl <- "http://geocoding.geo.census.gov/geocoder/locations/addressbatch"

addresses <- "1, 1 Infinite Loop, Cupertino, CA, 95014
2, 1 Hacker Way, Menlo Park, CA, 94025"

addresseFile <- "addresses.csv"
writeLines(addresses , addresseFile )

resp<-POST(apiurl, body=list(addressFile=upload_file(addresseFile), benchmark=4), 
     encode="multipart")
content(resp)

如果你想跳过写入csv文件到硬盘,你可以做

If you wanted to skip writing the csv file to disk, you could do

resp <- POST(apiurl, body=list(
    addressFile = RCurl::fileUpload(
      filename = "data.csv", 
      contents = addresses, 
      contentType = "application/octet-stream"
    ), 
    benchmark=4
  ), 
  encode="multipart"
)

这篇关于上传CSV以R中的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆