1

This might be something rather obvious for the real cracks here. Nevertheless! I dare asking the question. I was looking for a way to define an argument based on a second argument. I haven't found an answer for R, but this question helped me (I am not a python user, btw): python question

csv <- function(x, name = NULL) { #defines name as NULL

  if (is.null(name)) { #tests if name is NULL and when yes, 
                       #uses x for naming of the file
    file <- deparse(substitute(x))
    name <- paste0(file,'.csv')
    write.csv(x, name, row.names = F)

  } else {             #if name argument is defined , 
                       #then this will happen 
     name1 <- paste0(name,'.csv')
     write.csv(x, name1, row.names = F)
  }
}

This works. My csv-function uses as default the name of the first argument as file name.

I can now call csv() with

csv(my_df)

or

csv(my_df, 'creative_name')

I wondered, however, if there is a more elegant way than this conditional statement to do this kind of stuff. Cheers.

tjebo
  • 21,977
  • 7
  • 58
  • 94

1 Answers1

1

I think you can just do the following. Note that I have replaced the write_csv(x) statement with return(list(x)) for illustration purposes.

csv <- function(x, name = deparse(substitute(x))) {
  name1 <- paste0(name,'.csv')
  return(list(x, name1, row.names = F))    
}

y = head(mtcars,5)
csv(y)

Output:

[[1]]
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2

[[2]]
[1] "y.csv"

$row.names
[1] FALSE

Hope this helps!

Florian
  • 24,425
  • 4
  • 49
  • 80