0

I seek to implement a loop inside R to retrieve a series of dataframes. Moreover, I want to edit the dataframes inside the loop to tidy the data and set it up as a panel data format.

So, I used assign to be able to assign names inside a loop, such that I got:

for(i in 1:2){
    assign(paste("df", i, sep = ""), sim_inf10_mun(linha = "Município", coluna = "Ano do Óbito", periodo = c(1996:2016), municipio = "all", 
        capitulo_cid10 = i))
}

The "sim_inf10_mun" is simply a function that is taking some data online and making a dataframe (it requires library("datasus")). Such as, in this example, I get two dataframes: df1 and df2.

I'd like to conduct the following changes in a dataframe, say, df1,

df1 <- df1[-1,]
df1 <- df1[,-ncol(df1)]
df1 <- gather(df1, "ano", "deaths_1", 2:ncol(df1)) 
names(df1)[1]<-"cod_mun"
df1 <- transform(df1, cod_mun = substr(cod_mun, 1, 6))

These are simple changes involving variable names, dropping some lines, some columns, etc.

However, I have no idea on how to call df1 inside the loop. I understood how the "assign" function works, at least superficially, but I don't see how I can use it again to make the changes I want to make.

1 Answer 1

1

I've managed to achieve what I wanted. I'm posting it here in case it may help other people who are finding this difficult.

It was achieved by the simple use of a list.

data_list <- list()

for(i in 1:22){
data_list[[i]] <- sim_inf10_mun(linha = "Município", coluna = "Ano do Óbito", periodo = c(1996:2016), municipio = "all", 
                        capitulo_cid10 = i)
data_list[[i]] <- data.frame(data_list[i])
data_list[[i]] <- data_list[[i]][-1,]
data_list[[i]] <- data_list[[i]][,-ncol(data_list[[i]])]
data_list[[i]] <- gather(data_list[[i]], "ano", "deaths_1", 2:ncol(data_list[[i]])) 
names(data_list[[i]])[1]<-"cod_mun"
data_list[[i]] <- transform(data_list[[i]], cod_mun = substr(cod_mun, 1, 6))
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.