Selecting part of a data frame and saving in loop

4

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

    
asked by anonymous 10.07.2017 / 07:46

2 answers

4

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

The walk is a loop type that returns no results. With this code I'm asking that for every element of the distintos vector, R filter the data.frame by the variable cyl and then write that new data.frame to a file named var=valor_utilizado.csv" in the meudir directory. p>

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 value other than the cyl variable:

    
10.07.2017 / 13:40
0

Using mtcars with column cyl , follow example by looping with 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 csv s:

    
11.07.2017 / 05:16