使用 R 访问 URL 并读取数据 [英] Access a URL and read Data with R

查看:19
本文介绍了使用 R 访问 URL 并读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以指定网站 URL 中的数据并将其获取到 CSV 文件中,以便使用 R 进行分析?

Is there a way I can specify and get data from a web site URL on to a CSV file for analysis using R?

推荐答案

最简单的情况,就去做

X <- read.csv(url("http://some.where.net/data/foo.csv"))

加上 read.csv() 可能需要的选项.

plus which ever options read.csv() may need.

在 2020 年 9 月或 9 年后

几年来,R 还支持将 URL 直接传递给 read.csv:

For a few years now R also supports directly passing the URL to read.csv:

X <- read.csv("http://some.where.net/data/foo.csv")

2020 年底编辑.原帖继续.

长答案:是的,这是可以做到的,许多软件包多年来一直在使用该功能.例如.tseries 软件包正是使用此功能从 Yahoo! 下载股票价格!近十年:

Long answer: Yes this can be done and many packages have use that feature for years. E.g. the tseries packages uses exactly this feature to download stock prices from Yahoo! for almost a decade:

R> library(tseries)
Loading required package: quadprog
Loading required package: zoo

    ‘tseries’ version: 0.10-24

    ‘tseries’ is a package for time series analysis and computational finance.

    See ‘library(help="tseries")’ for details.

R> get.hist.quote("IBM")
trying URL 'http://chart.yahoo.com/table.csv?    ## manual linebreak here
  s=IBM&a=0&b=02&c=1991&d=5&e=08&f=2011&g=d&q=q&y=0&z=IBM&x=.csv'
Content type 'text/csv' length unknown
opened URL
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
........
downloaded 258 Kb

             Open   High    Low  Close
1991-01-02 112.87 113.75 112.12 112.12
1991-01-03 112.37 113.87 112.25 112.50
1991-01-04 112.75 113.00 111.87 112.12
1991-01-07 111.37 111.87 110.00 110.25
1991-01-08 110.37 110.37 108.75 109.00
1991-01-09 109.75 110.75 106.75 106.87
[...]

help(connection)help(url) 的手册页中详细记录了这些内容.另请参阅 R 附带的数据导入/导出"手册.

This is all exceedingly well documented in the manual pages for help(connection) and help(url). Also see the manul on 'Data Import/Export' that came with R.

这篇关于使用 R 访问 URL 并读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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