2

For some reason, my work requires me to update a certain variable in multiple R files on a daily basis (for demonstration, I use date.updated as the variable name).

I am wondering if there is any way that I can automate this process:

  1. Open and Locate the line date.updated = as.Date('XXXX-01-01')
  2. Change the line to date.updated = as.Date('XXXX-01-02')
  3. Save the R file under the same name and directory

Thank you in advance!

2
  • 1
    Is date.updated supposed to be today's date? If so, you could simply use date.updated = Sys.date(). Commented Jun 23, 2020 at 15:13
  • Since we do not update strictly every day, for some days, we still need date.updated remain as a previous date. Commented Jun 23, 2020 at 15:17

1 Answer 1

1

Starting with a basic .R file with only one line to be replaced:

some(code)
date.updated = as.Date('2020-01-01')
date.updated = as.Date('2020/01/01')
list.files()

On a shell (e.g., bash), one can use sed -i -E "..." file.R to change all matching lines in-place. This is analogous to sed -E "..." < file.R > newfile.R. (Some file-systems don't do well with -i, so you might need the second option anyway.)

Using that, I'll demonstrate without replacing the file, for expediency.

$ sed -E "s/^(date\.updated\s*=\s*as\.Date)\('[-0-9]{10}'\)\s*$/\1('2020-01-02')/g" 62537920.R
some(code)
date.updated = as.Date('2020-01-02')
date.updated = as.Date('2020/01/01')
list.files()

If you want it to be changed programmatically to today's date, you can use

$ sed -E "s/^(date\.updated\s*=\s*as\.Date)\('[-0-9]{10}'\)\s*$/\1('$(date +%Y-%m-%d)')/g" 62537920.R
some(code)
date.updated = as.Date('2020-06-23')
date.updated = as.Date('2020/01/01')
list.files()

(I included a second date.updated line purely to demonstrate the specificity of the pattern.)

R typically has access to sed (either natively on unix/macos or via Rtools on windows), though on Windows you might need to specify its full path. If you really want to do this from R, then you can use system, system2, or processx::run.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.