0

I am trying to understand how to write a loop in R to rename a variable number of data frames.
If I run this code:

library("readxl")
path <- readxl_example("datasets.xls")
MyObject<-lapply(excel_sheets(path), read_excel, path = path)

I get an object that contains 4 tibbles. If I want to rename them as File1 - File4, I can use

File1<-MyObject[[1]] 

And so on for each one separately. However, I am dealing with files that have varying numbers of worksheets, and so end up with variable numbers of dataframes in my object. So my question is; how do I tell R to rename each tibble as File1, File2, etc for as many tibbles are in the object? I would welcome a specific answer, but if there is a tutorial out there that talks about writing loops (for beginners) that people recommend, I would welcome that as well.

Lina Bird
  • 451
  • 1
  • 6
  • 11
  • Is it just about the renaming? or what is your goal with the single tibbles? – Val Jun 13 '17 at 14:02
  • Do you mean variable numbers of worksheets? – Elin Jun 13 '17 at 14:04
  • @Val To expand: I have data that comes off the instrument as a separate spreadsheet for each day, with the exact same variables, in each sheet. I want to combine the spreadsheets into a single data frame so that I can plot it all together. The command I know for this is rbind, but 'rbind(MyObject[[1]])' returns an error of "MyObject not found". So my solution was to extract each tibble as a separate data set, which then works with rbind. – Lina Bird Jun 13 '17 at 15:06

2 Answers2

2

Does this do what you want? A basic R loop is just something like for (i in start:end) {}

for (i in 1:length(MyObject)) {
    assign(paste0("File", i), MyObject[[i]])
}
Consistency
  • 2,884
  • 15
  • 23
2

Knowing what you just commented, I can suggest a solution which is IMHO superior to a loop:

Since you used lapply to load your excel sheets, I assume that MyObject is a list of single data.frames.

So to combine them to a single data.frame, just run alldfs <- do.call(rbind,MyObject).

That should give you one single data.frame without any looping or single variables.

Val
  • 6,585
  • 5
  • 22
  • 52