0

I have a set of data frames for each month of 2020:

    FR_01_2020
    
    FR_02_2020
    
    FR_03_2020

    .

    .
 
    .
 
    FR_12_2020

I'd apprecaite it if you could answer two questions :

  1. How can I create a list (called All_months) using these tables and by using a loop ?

In other words, I want to avoid the traditional method :

All_months <- list(FR_01_2020, ..., FR_12_2020)
  1. How can I define new data frames based on FR_01_2020 ... FR_12_2020 using a loop and without using the list we just created in part 1 ?

In other words something like this (of course it is wrong but it delivers the concept I am looking for)

 for (i in 1:12) {
table_i <- FR_i_2020}

So the result is table_1, table_2 ... table_12.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Afshin Sh
  • 51
  • 4
  • Creating a `list` is better. To create new objects, use `assign`, i.e. `assign(paste0("table_", i), get(paste0("FR_", i, "_2020"))` – akrun Apr 01 '22 at 17:51
  • 1
    Don't use a `for` loop, perhaps `mget(ls(pattern="^FR_"))`. Then you can either combine them (`do.call(rbind,..)`, `dplyr::bind_rows(..)`, or `data.table::rbindlist(..)`) or continue working with them as a [list of frames](https://stackoverflow.com/a/24376207/3358227). – r2evans Apr 01 '22 at 17:52

1 Answers1

2

as @akrun advises, you should use lists. Fundamentally with a loop you just "append" items to an empty list using c():

With for loops- you need to read the data(presumably a csv/xsl file) and covert each into a data frame and then append it. lets say you have mtcars.csv and iris.csv saved in a folder of your choice.

get them with x <-list.files(path = getwd(),pattern = "*.\\.csv",full.names = T) Now this worked to get me a list of file paths. You can modify the code in a for loop and convert each file to a data.frame and keep joining them:

x <- list.files(path = getwd(),pattern = "*.\\.csv",full.names = T)

listOffile <- list()

for(i in 1: length(x)){
  listOffile <- c(listOffile, x[i])
  print(x[i])
}

output is a list :

str(listOffile)

For the second question :

If you are just renaming the files, you can run another loop with change of name using newName<-paste("Table_",i) and then using c(). Since am not clear about this question, cannot try in dark.

`

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
anuanand
  • 400
  • 1
  • 9