J Miller
J Miller

Reputation: 437

problem creating dynamic file name in R

I'm working on a script in R that processes some data and writes an output file. I'd like that output file to be named in a way that reflects the input file, and I'd like something about the file to be unique so older files aren't overwritten.

So I thought to use a timestamp. But this isn't working the way I'd hoped, and I'd like to understand what's happening and how to do this correctly.

This is how I'm trying to name the file (file_base is the name of the input file):

now<-format(Sys.time(), "%b%d%H%M%S")
outputfile<-cat(file_base, "-",now,"-output.txt", sep="")

The output of this pair of functions looks great. But executing 'outputfile' subsequently results in 'NULL' as output.

What's happening here and how can I create an output filename with the properties that I'd like?

Upvotes: 8

Views: 13125

Answers (4)

trupthi
trupthi

Reputation: 81

Let's say your input variable is input_file

Extract input_file as a string:

input_name <- deparse(substitute(input_file))

Name the output figure/ file as follows:

output_name <- sprintf("TheNameIs%s_%s.png", input_name,
                           gsub(Sys.Date(), pattern = "-",replacement = "_"))

I like to incorporate timestamps in my file name so that the functions dynamically name the output files/images. I did not use time, because the date stamp is more than enough for my use-case.

Use this output_name string in saving function.

For example:

ggsave(
  filename = here("folder1/folder2/folder3",output_name),
  device = 'png'
   )

Upvotes: 0

CcMango
CcMango

Reputation: 437

You can also use the function sprintf(), it's a wrapper for the C function. example:

filepath <- file.path(outdir, sprintf("abcdefg_%s.rda", name))

Upvotes: 0

brunj7
brunj7

Reputation: 149

You could also use the separator argument of paste:

outputfile <- paste(file_base,now,"output.txt", sep="-")

Upvotes: -2

Joshua Ulrich
Joshua Ulrich

Reputation: 176718

You're confusing cat and paste. You want:

outputfile <- paste(file_base, "-",now,"-output.txt", sep="")

Upvotes: 16

Related Questions