Function exporting CSV files fails

Hello,
I'm learning functions in R using tidyverse.
I want to filter and export results to a CSV file.
Here is the code:

library(tidyverse)
library(gapminder)
rm(list=ls())
datos<-gapminder::gapminder

unique_continents<-datos %>% distinct(continent) %>% pull() %>% as_vector()

example1 <- function(x) {
  continent_data <- datos %>%
    filter(continent == x)
  return(continent_data)
  
  filename <- paste0(x, ".csv")
  write_csv2(continent_data, file = filename, row.names = FALSE)
}

example1("Americas")
map(unique_continents,example2)

When I run the code using map(... I noticed on console that I slice the data as I wanted.
But the function doesn't export any CSV file.
What am I doing wrong?
It's very simple, but at the end I failed.
Thanks for your time and interest.
Have a nice week, community.

Hi @jfca283 ,

It's important to note that return(continent_data) essentially marks the end of your function. That's the job of return(). So you should put it at the very bottom of the function.

# Create function

example1 <- function(x) {
  
  continent_data <- gapminder::gapminder %>%
    filter(continent == x)
  
  filename <- paste0(x, ".csv")
  write_csv2(continent_data, file = filename)
  
  return(continent_data)
}

example1("Americas")
1 Like

Thanks, gueyenono.
I was very lost before your post.
Thanks again.

I'm glad I could help :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.