rmuc8
rmuc8

Reputation: 2989

Filename contains variable - how to apply to R functions

x is a variable with a name like

x <- "Smith"

I want to use a function that does something like

> write.csv(dataframe,file="Bookkeeping_x.csv")

It should return a file called Bookkeeping_Smith.csv

My desired solution is to call a function > do_bookkeeping(x) with

> do_bookkeeping <- function(x)
> {
  ........
> write.csv(dataframe,file="Bookkeeping_x.csv")
> ........
> }

I want the function do_bookkeeping(x) to create a file

Bookkeeping_Smith.csv

Upvotes: 0

Views: 130

Answers (2)

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

Try:

write.csv(dataframe,file=paste0("Bookkeeping_",x,".csv"))

Upvotes: 2

jbaums
jbaums

Reputation: 27388

sprintf is handy for this:

do_bookkeeping <- function(x) {
  write.csv(dataframe, file=sprintf('Bookkeeping_%s.csv', x))
}

The %s is replaced by the second argument to sprintf, i.e. x.

See ?sprintf for more details.

Upvotes: 1

Related Questions