Include Files R

Include files R?

Use source and/or sys.source.

(How) is it possible in R to include external files with source code

the command you are looking for is source() - check out ?source for further information. An alternative is sys.source()

how to do R includes

Maybe you are just looking for source(file="include.R"). Note that source() executes the commands in the specified file, it does not (like PHP include) simply paste the contents of that file into the including file. Which is probably not important in your case.

R: Possible to include some header files?

Just make a R source file, e.g. my_header.R and use the function source to include all variables defined in this file in all your scripts. You can just include the file with source('my_header.R'). Does this help?

R: source() and path to source files

If you are distributing a script to colleagues, you should really not be writing a script that sources other scripts. What if you want to rename or move functions.R in the future? What if you need to modify a function in functions.R, but wrapper.R relies on the older version of that function? It's a flimsy solution that will cause headache. I would recommend either of the following instead.

  1. Put everything needed into a single, self-contained script and distribute that.

  2. If you really want to separate code into different files, write a package. Might sound like overkill, but packages can actually be very simple and lightweight. In the simplest form a package is just a directory with a DESCRIPTION and NAMESPACE file along with an R/ directory. Hadley breaks this down nicely: https://r-pkgs.org/whole-game.html.

List files pattern with AND condition in R

You can select the files that start with "Coca_cola" which will also drop the temporary files that begin with "~".

Files <- list.files(pattern= "^Coca_cola")

Include pattern in list.dirs

Three alternatives:

dirs <- list.dirs()
dirs <- dirs[ grepl(your_pattern, dirs) ]

or

dirs <- list.dirs()
dirs <- grep(your_pattern, dirs, value = TRUE)

or

files <- list.files(pattern = your_pattern, recursive = TRUE, include.dirs = TRUE)
dirs <- files[ file.info(files)$isdir ]

How to include (source) R script in other scripts

Here is one possible way. Use the exists function to check for something unique in your util.R code.

For example:

if(!exists("foo", mode="function")) source("util.R")

(Edited to include mode="function", as Gavin Simpson pointed out)

list.files() on a specific sub-directory in a folder tree

Here’s one way:

dirs = list.dirs('main')
proj_doc_dirs = grep('/proj./proj[ _]doc', dirs, value = TRUE)
txt_files = dir(proj_doc_dirs, pattern = '\\.txt$', full.names = TRUE)


Related Topics



Leave a reply



Submit