Nonfunctional Function

I am running this code from readr to import data and it functions perfectly"

df <- read_csv("Dataset.csv", col_names = TRUE, col_types = cols_only(VAR1, VAR2, VAR3)

I want to make it into a function so I can run it on multiple inputs, so I wrote this code:

extract_function <- function(x) {
df <- read_csv(x, col_names = TRUE, col_types = cols_only(VAR1, VAR2, VAR3)}

The function is created but when I execute the function it chunks through everything (looks like its working) but never creates the new data frame. Heres how I have been executing the function:

extract_function ("Dataset.csv")

  1. Why isn't it creating my new data frame once I put it into the function?
  2. How can I name the new data frame based on the input from csv? (would like the new dataframe to have the same name as the csv it extracted from)

The function is not written to return anything. It does make the object df but the disappears once the function is done running. Try

extract_function <- function(x) {
  read_csv(x, col_names = TRUE, col_types = cols_only(VAR1, VAR2, VAR3)
1 Like

for the first question, you need to add the line return(df) or just df.
when you df <- extract_function("Dataset.csv") , the df will contain your data.frame.

for the second question, instead of return, you would need to assign(x,df) .
In general x is the name you want to give to df.
By default this will create x in the global environment.
Look at the documentation to modify this.

1 Like

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