Error when trying to write to CSV with a variable in the file name (but no error if don't use function)
Error when trying to write to CSV with a variable in the file name (but no error if don't use function)
I created a function clean_to_CSV(df)
that takes in a data frame, cleans it, spits it back out, and also writes it to a CSV, with the CSV's filename using the inputted name of the dataset:
clean_to_CSV(df)
clean_to_CSV <- function(df)
# df <- # code that cleans the df (runs with no errors)
write.csv(df, file = paste0(deparse(substitute(df)), "_clean.csv"), row.names = FALSE)
df
However, this returns:
Error in file(file, ifelse(append, "a", "w")) :
invalid 'description' argument
In addition: Warning messages:
3: In if (file == "") file <- stdout() else if (is.character(file)) { :
the condition has length > 1 and only the first element will be used
This is very puzzling because 1) taking the exact same write.csv... line and running it outside the function works perfectly. Also, I know that writing to CSV and returning the df don't interfere with each other. Finally, I did look at related SO posts, but they were either more complex questions or didn't have a solid answer. None were such a simple case where one line of code works outside a function but not inside it.
deparse(substitute(...))
What if you input
df
as text? The code then becomes write.csv(get(df), file = paste0(df, "_clean.csv"), row.names = FALSE)
– Tung
Jun 23 '16 at 18:20
df
write.csv(get(df), file = paste0(df, "_clean.csv"), row.names = FALSE)
I cannot reproduce the error.
clean_to_CSV(mtcars)
works as expected.– Stibu
Jun 23 '16 at 20:11
clean_to_CSV(mtcars)
Thanks for your replies. The dataset and cleaning code I'm using are too specialized/complicated to reproduce, and prob not worth it for solving such a minor problem. I'll keep running the write.csv statement outside the function for now.
– gnotnek
Jun 28 '16 at 23:12
1 Answer
1
After you apply the cleaning code (the part you commented out), df
has a different representation that no longer has the name it had when it was an argument value.
df
To fix it, just capture the name of the object as soon as you enter the function, and then reference that value later. Here's an example.
clean_to_CSV <- function(df)
obj_name = deparse(substitute(df))
# df <- # code that cleans the df (runs with no errors)
write.csv(df, file = paste0(obj_name, "_clean.csv"), row.names = FALSE)
df
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
Can you provide the code that generated that error? When dealing with
deparse(substitute(...))
, it can get "interesting" very quickly.– r2evans
Jun 23 '16 at 18:16