将csv上传到R中的api [英] Uploading a csv to an api in R

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

问题描述

为了调用人口普查地理编码器 api,我使用了 http 上的文档中的提示://geocoding.geo.census.gov/geocoder/Geocoding_Services_API.pdf 在批量地理编码"标题下.他们给出的用于调用批处理的 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 中执行上述命令的等效方法是什么?RCurl 包中的 postForm() 可以做到这一点吗?

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


顺便说一句,上传的 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

因此,例如,它可以只包含像 Apple 和 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天全站免登陆