-2

I have access from scraped government data, which comes in a less the useful structure. Its 20 dfs that looks like:

enter image description here

Each df is named by the year, eg, X2006.csv is imported in a X2006 dataframe object. They all have a Total row and a total column, which I will deal with later. Now, my question is:

  • How do I merge these dfs, adding a column with the year information from the dataframe name?
lf_araujo
  • 1,991
  • 2
  • 16
  • 39
  • 2
    Do not post your data as an image, please learn how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – Jaap Jun 03 '18 at 14:05
  • 1
    [See this Q&A for a possible apporach](https://stackoverflow.com/q/32888757/2204410) – Jaap Jun 03 '18 at 14:07
  • Please post code as well in how you import into individual year dfs. – Parfait Jun 03 '18 at 14:28

2 Answers2

1

Instead of using loop you can use do.call:

require(tidyverse)

#Creating sample data set - 10 data.frames
for (i in 1:9){
  assign(paste("x200", i, sep=""),
         data.frame(x = c(1:20)))
  }


#Creating the big data.frame
MyBigDataframe <- do.call(rbind.data.frame, mget(ls(pattern = "x20"))) %>% 
  rownames_to_column("file")
DJV
  • 4,743
  • 3
  • 19
  • 34
0
startYear <- 1998
endYear <- 2017

myData <- data.frame()

require(plyr)

for (myYear in startYear:endYear){
    df <- get(paste0("X", as.character(myYear)))

    df$Year <- myYear

    myData <- rbind.fill(myData, df)
}
Thomas Wire
  • 272
  • 1
  • 9