Afshin Sh
Afshin Sh

Reputation: 51

looping over consecutive tables name in R

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.

Upvotes: 0

Views: 40

Answers (1)

anuanand
anuanand

Reputation: 400

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.

`

Upvotes: 2

Related Questions