简体   繁体   中英

Read many Excel files from R

It's my first time with R, so maybe the problem is trivial

I need to download date from xls files from url and each one should be in one data frame. Like here .

I decided to use gdata package (package 'xlsReadWrite' is not available for R version 3.1.0, RODBC not available for win64)

Downloading works great for one file (year eg = 2013 )

readxls<-function()
{
  library("gdata")
  link<-paste0("http://nbp.pl/kursy/archiwum/archiwum_tab_a_",year,".xls")
  xlsdata <<- read.xls(link, sheet = 1, perl = "C:\\Perl64\\bin\\perl.exe", header=TRUE) 
}

I tried to read many .xls into list() using loop. (eg y_begin=2012, y_end=2014)

readxls<-function()
{
  library("gdata")

  ldata<<- list()
  j=1
  for (i in y_begin:y_end)
  {
    link<-paste0("http://nbp.pl/kursy/archiwum/archiwum_tab_a_",i,".xls")
    xlsdata <<- read.xls(link, sheet = 1, perl = "C:\\Perl64\\bin\\perl.exe", header=TRUE) 

    ldata[j] <<- xlsdata
    j<-j+1
  }
}

I thought that after that I'd be able to merge them, but don't know how to get data from single data frame in list for example > View(ldata[2]) returns only first collumn

Avoid use for loop , specially for its side effect. Better to use lapply here. It is the R way to do things ( functional programming). Here I would do this:

library(gdata)
readxls<-function()
{
  ids <- seq(y_begin,y_end)
  links <-paste0("http://nbp.pl/kursy/archiwum/archiwum_tab_a_",ids,".xls")

  lapply (links,function(i)
     read.xls(link, sheet = 1, perl = "C:\\Perl64\\bin\\perl.exe", header=TRUE) 
  )
}

This will return a list of data.frame, to merge them, assuming that they are ll the same:

ll <- readxls()
do.call(rbind,ll)

Thank you so much, but the answer was easier. It's enought to make ldata[[j]]

readxls<-function()
{
  library("gdata")

  ldata<<- list()
  j=1
  for (i in y_begin:y_end)
  {
    link<-paste0("http://nbp.pl/kursy/archiwum/archiwum_tab_a_",i,".xls")
    xlsdata <<- read.xls(link, sheet = 1, perl = "C:\\Perl64\\bin\\perl.exe", header=TRUE) 

    ldata[[j]] <<- xlsdata
    j<-j+1
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM