How can I name objects in R according to a for loop?

1.1k Views Asked by At

I'd like to name objects in a loop depending on i. I've got datasets from 1996 to 2020, all called Natalidad i_p.csv where i is the year. Each of them have the variables ano and mes. I want to create a matrix for each year with those two variables and name each of them matrix_i (where i is the year). I've tried the next code with and without the assign function, but it isn't working.

for (i in 1996:2020) { 
nacimientos <- read.csv(paste0("C:/Users/.../Natalidad ", i, "_p.csv"), header = TRUE, sep = ";")
assign(paste0("matrix", i), i) <- melt(table(nacimientos$ano, nacimientos$mes))
}
1

There are 1 best solutions below

0
On

We can assign names to an object with names()[i]<-"name". First, create an output object to be populated. Then populate it with your loop.

    output<-vector('list', length(1996:2020))
    for (i in as.character(1996:2020)) { 
    nacimientos <- read.csv(paste0("C:/Users/.../Natalidad ", i, "_p.csv"), header = TRUE, sep = ";")
    output[i]<-melt(table(nacimientos$ano, nacimientos$mes))
    names(output)[i]<-paste0("matrix_", i)
    }

this will create a list of matrixes, in which every element is named "matrix_i"