How to make a loop / routine for the write.fst () function?

4

I have the following files in my working directory:

Dados_1.fst
Dados_2.fst
Dados_3.fst
Dados_4.fst
...
Dados_10.fst

The file Data_x.fst (where x is from 1 to 10) has the columns CODE, INSCRIPTION, ANSWER_A, ANSWER_B

Then I create the following data frames:

df.1 <- select(filter(read.fst("Dados_1.fst"), CODIGO ==     
10102),INSCRICAO,RESPOSTAS_A,RESPOSTAS_B)
df.2 <- select(filter(read.fst("Dados_2.fst"), CODIGO ==
10102),INSCRICAO,RESPOSTAS_A,RESPOSTAS_B)
df.3 <- select(filter(read.fst("Dados_3.fst"), CODIGO == 
10102),INSCRICAO,RESPOSTAS_A,RESPOSTAS_B)
...
df.10 <- select(filter(read.fst("Dados_10.fst"), CODIGO == 
10102),INSCRICAO,RESPOSTAS_A,RESPOSTAS_B)

I would like to loop such that I did not have to write the above code 10 times.

I tried to follow the path below, but without success

for (i in 1:10)
{
paste("df",i, sep =".") <- select(filter(read.fst(paste(paste("Dados",i,sep="_"),"fst",sep =".")), 
CODIGO == 10102),INSCRICAO,RESPOSTAS_A,RESPOSTAS_B)
 }

Up to +

    
asked by anonymous 16.05.2018 / 21:28

2 answers

4

To do what you want, it is best to use lapply by applying to each element of the%% vector the anonymous function that reads Dados . The value of fl is an object of class lapply , and each table will be a member of that list. This is much better than having 10 tables in list .

Dados <- list.files(pattern = "Dados_[[:digit:]]+\.fst")

df_list <- lapply(Dados, function(fl){
    select(filter(read.fst(fl), CODIGO == 10102), INSCRICAO, RESPOSTAS_A, RESPOSTAS_B)
})

names(df_list) <- paste("df", seq_along(Dados), sep = ".")

df_list$df.1         # primeira tabela
df_list[["df.1"]]    # a mesma tabela, repare que "df.1" é uma string
df_list[[1]]         # a mesma tabela
    
17.05.2018 / 14:09
0

You need to dynamically create the variables and for this R can use assign .

x = 1:10
for (i in 1:10)
{
    assign(paste("df", i, sep="."), x[i]) = select(filter(read.fst(paste(paste("Dados",i,sep="_"),"fst",sep =".")), 
CODIGO == 10102),INSCRICAO,RESPOSTAS_A,RESPOSTAS_B)
}

Fonts

Using assign num for loop: StackOveflow in English

    
16.05.2018 / 21:45