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

Asked

Viewed 101 times

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 Dados_x.fst file (where x goes from 1 to 10) has the columns CODIGO, INSCRIPTION, RESPOSTAS_A, RESPOSTAS_B

Hence 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 in such a way that I don’t need to write the above code 10 times.

I tried to follow the way down, but to no avail

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 until+

2 answers

4


To do what you want, it’s best to use the lapply applying to each element of the vector Dados the anonymous function that reads the files fl.
The value of lapply is a class object list, and each table will be a member of that list. That’s much better than having 10 tables on GlobalEnv.

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
  • It worked well! Thank you ;)

0

You need to create variables dynamically and for that 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)
}

Sources

Use of assign num for loop: Stackoveflow in English

  • You’re making that mistake Error in assign(Paste("df", i, Sep = "." ), x[i]) = select(filter(read.fst(Paste("Data", : target of assignment expands to non-language Object Am I doing something wrong?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.