Selecting part of a data frame and saving in loop

Asked

Viewed 291 times

4

I have a date frame of more than 1000 rows and two columns (col1 and col2). How do I select n data frames (subsets of the original data frame) based on column 2 (only the same elements) by means of a loop and then save n data.frames (df1, df2,...dfn) to a tb directory in the loop?

2 answers

4

I would do something like this, in the example considering the data frame. mtcars which is already available on R.

The walk is a kind of loop that returns no results. With this code I am asking that for each element of the vector distintos, o R Construct the data.frame by variable cyl and then write this new data.frame in a file called var=valor_utilizado.csv" in the directory meudir.

library(purrr)
distintos <- unique(mtcars$cyl)
walk(distintos, ~mtcars[mtcars$cyl == .x,] %>% 
       write.csv(paste0("meudir/var=", .x, ".csv"))
)

This will create 3 files, one for each distinct variable value cyl:

inserir a descrição da imagem aqui

0

Also using the mtcars with the column cyl, follows example by making a loop with the for:

for(i in seq_along(unique(mtcars$cyl)))
  write.csv(subset(mtcars, cyl == unique(mtcars$cyl)[[i]]), paste0("df", i,".csv"))

As a result we have the 3 csvs:

inserir a descrição da imagem aqui

Browser other questions tagged

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