How to write the dataframes in a list to a single csv file

前端 未结 2 1110
有刺的猬
有刺的猬 2021-01-16 11:48

I have a list with 15 data frames and they look like this

> head(final_data[[1]])
      DateTime # Unemployed Persons.csv
147 2013-03-01                          


        
相关标签:
2条回答
  • 2021-01-16 12:16

    We can use Reduce with merge

    Reduce(function(...) merge(..., by = "DateTime"), final_data)
    #    DateTime Unemployed_Persons.csv Business_Confidence.csv
    #1 2013-03-01                2320.58                    -6.2
    #2 2013-04-01                2336.89                    -1.3
    #3 2013-05-01                2213.78                    -2.4
    #4 2013-06-01                2135.90                    -5.1
    #5 2013-07-01                2302.79                    -2.0
    #6 2013-08-01                2177.01                    -1.8
    

    data

     final_data <- list(structure(list(DateTime = c("2013-03-01", "2013-04-01", 
    "2013-05-01", "2013-06-01", "2013-07-01", "2013-08-01"), Unemployed_Persons.csv = c(2320.58, 
    2336.89, 2213.78, 2135.9, 2302.79, 2177.01)), .Names = c("DateTime", 
    "Unemployed_Persons.csv"), class = "data.frame", row.names = c("147", 
    "148", "149", "150", "151", "152")), structure(list(DateTime = c("2013-03-01", 
    "2013-04-01", "2013-05-01", "2013-06-01", "2013-07-01", "2013-08-01"
    ), Business_Confidence.csv = c(-6.2, -1.3, -2.4, -5.1, -2, -1.8
    )), .Names = c("DateTime", "Business_Confidence.csv"), class = "data.frame", row.names = c("46", 
    "47", "48", "49", "50", "51")))
    
    0 讨论(0)
  • 2021-01-16 12:30

    you can use the join-functions from the dplyr-package an put them in a loop like this:

    library(dplyr)
    #example list
    list <- list(
      data.frame("Date" = seq(as.Date("2016-01-01"), as.Date("2016-02-01"), "days"), 
                 "a" = 1:32), 
      data.frame("Date" = seq(as.Date("2016-01-01"), as.Date("2016-02-01"), "days"), 
                 "b" = 33:64), 
      data.frame("Date" = seq(as.Date("2016-01-01"), as.Date("2016-02-01"), "days"), 
                 "c" = 65:96))
    
    for (i in 1:length(list))
      if(i == 1) df <- list[[1]] else
        df <- left_join(df, list[[i]])
    
    0 讨论(0)
提交回复
热议问题