looping with dplyr in R

Asked

Viewed 37 times

1

I’ve been looking for a solution to a question for days. I intend to create a repeating structure that allows to save a table for each class according to the code below, filtering and saving automatically, without needing to replace the letters of "Classe1" one by one.

library(dplyr)

id = c(1:20)
classe1 = as.factor(c("a","a","b","c","b","c","a","a","a","a","c","c","b","b","a","c","b","b","b", "c"))
classe2 = as.factor(c("alfa","alfa","gama","gama","gama","alfa","gama","alfa","gama","gama","gama","alfa","gama","gama","gama","alfa","alfa","alfa","alfa", "gama"))
tabela <- data.frame(id, classe1, classe2)

teste <- tabela %>%
  filter(classe1 == "a")%>%
  group_by(classe2) %>%
  summarise(n=length(id))
       
write.table(teste, "a.csv", row.names = F) 

intended, with this function, generate and save in the directory three files . csv, named... dplyr ta right... out of function it works. But the function... although returns without error, does not generate anything. where I am missing here

The function:

level<-c("a", "b", "c")
level<- as.factor(level)  

for(i in 1:length(level)){

  teste <- tabela %>%
    filter(classe1 == print(paste(level[i])))%>%
    group_by(classe2) %>%
    summarise(n=length(id))
      
  write.table(teste, paste0(raiz, level[i],'.csv'), row.names = F) 
}
  • 1

    This is completely unnecessary: print(paste(level[i])). Only level[i] does exactly the same, try.

1 answer

2

Here is a function that divides the table by values of "classe1" and writes the corresponding files. Tested with raiz as defined below.

fun_dplyr <- function(x, col, raiz){
  x %>%
    group_split(!!sym(col)) %>% 
    purrr::map(~write.table(.x, paste0(raiz, first(.x[[col]]), ".csv"), row.names = FALSE))
}

raiz <- "~/tmp/"

fun_dplyr(tabela, col = "classe1", raiz)

Browser other questions tagged

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