【问题标题】:How can I read a table from a URL and keep it as a dataframe?如何从 URL 读取表格并将其保存为数据框?
【发布时间】:2017-11-10 07:18:42
【问题描述】:

我对函数 read.table 有疑问。我想从一个 url 中读取一个表,并将其作为数据框保存在 R 中。网址是: https://datanalytics.com/uploads/datos_treemap.txt

我已经写了这段代码:

library(RCurl)

a <- getURL('https://datanalytics.com/uploads/datos_treemap.txt')
b = read.table(a, sep="\t ", header = TRUE, nrows=3)

download.file("https://datanalytics.com/uploads/datos_treemap.txt","/mnt/M/Ana/R/datos_treemap.txt",method = c("wget"))

但我无法将数据保存为数据框,并导致以下错误:

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") : cannot open file...
No such file or directory

我也尝试将文档下载为 txt,并将其保存在 mi PC 中。但是生成 txt 会产生一个向量而不是一个表(所有结果都在一个 unic 行中)。我写的代码是:

download.file("https://datanalytics.com/uploads/datos_treemap.txt","/mnt/M/Ana/R/datos_treemap.txt",method = c("wget"))

我做错了什么?

【问题讨论】:

    标签: r url dataframe read.table


    【解决方案1】:
    library(RCurl)
    a <- getURL('https://datanalytics.com/uploads/datos_treemap.txt')
    b <- read.table(text=a, header = TRUE)
    

    【讨论】:

      【解决方案2】:

      这里使用rvest而不是RCurl的另一个解决方案。我不想判断哪个包“更好”,只是想显示一个附加选项,尽管在您的简单情况下rvest 似乎更冗长,您需要 SelectorGadget 来识别所需的节点(如果有人请纠正我我错了,代码可以缩短)。

      library(rvest)
      
      table <- read_html("https://datanalytics.com/uploads/datos_treemap.txt") %>% 
               html_text("p") %>% 
               { read.table(text = ., header = T) }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-05
        • 2021-09-20
        • 2018-11-11
        相关资源
        最近更新 更多