2019-05-04

Read data from URL in R

Problem

How can we read data from an URL in R? We have a URL pointing to a text file, and we'd like to read it directly in R without previously downloading it to our computer.

http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv

Solution

We just need to pass the URL string inside the appropriate function. Apart from read.csv from the base package, I include a couple of examples from two popular packages: data.table y readr.

  • Base
  • ad <- read.csv("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
    head(ad)
    
      X    TV radio newspaper sales
    1 1 230.1  37.8      69.2  22.1
    2 2  44.5  39.3      45.1  10.4
    3 3  17.2  45.9      69.3   9.3
    4 4 151.5  41.3      58.5  18.5
    5 5 180.8  10.8      58.4  12.9
    6 6   8.7  48.9      75.0   7.2
    
  • data.table
  • library(data.table)
    ad <- fread("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
    head(ad)
    
    V1    TV radio newspaper sales
    1:  1 230.1  37.8      69.2  22.1
    2:  2  44.5  39.3      45.1  10.4
    3:  3  17.2  45.9      69.3   9.3
    4:  4 151.5  41.3      58.5  18.5
    5:  5 180.8  10.8      58.4  12.9
    6:  6   8.7  48.9      75.0   7.2
    
  • readr
  • library(readr)
    ad <- read_csv("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
    head(ad)
    
    # A tibble: 6 x 5
         X1    TV radio newspaper sales
              
    1     1 230.1  37.8      69.2  22.1
    2     2  44.5  39.3      45.1  10.4
    3     3  17.2  45.9      69.3   9.3
    4     4 151.5  41.3      58.5  18.5
    5     5 180.8  10.8      58.4  12.9
    6     6   8.7  48.9      75.0   7.2
    

Related posts

References

No hay comentarios:

Publicar un comentario

Nube de datos