Blaszard
Blaszard

Reputation: 31963

How to unfold user and environment variable in R language?

Are there any ways to expand tilde and environment variables in R?

For example, in Python, you can get it by writing out the following set of codes:

import os
os.path.expanduser("~/r_workspace") # return "/Users/yourname/r_workspace" (in OS X)
os.path.expandvars("$R") # return "/Users/yourname/r_workspace", if you set "$R" to it in advance

Does R provide the sort of functions? I don't like to bother to write the following code:

read.csv("/Users/myname/python_workspace/subdirectory_1/subdirectory_2/data.csv")

Upvotes: 2

Views: 2856

Answers (2)

Holger Brandl
Holger Brandl

Reputation: 11192

A more generic solution would be do unfold all environment variables into a dedicated R environment and interpolate strings of interest against it using glue.

require(purrr)
require(glue)


interp_from_env = function(path){
    e <- new.env()
    env = Sys.getenv()

    paste0(make.names(names(env)), "='", gsub("'", '', env), "'") %>%
        map(~eval(parse(text=.), envir=e))

    glue::glue(path, .envir=e, .open="${")
}

#usage examples
read.delim(interp_from_env("${PRJ_DATA}/foo.txt") )
source(interp_from_env("${HOME}/bar.R"))

Upvotes: 1

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

Pretty much the same!

path.expand("~")
#[1] "/Users/Simon"

path.expand will expand a path name by replacing a leading tilde by the user's home directory (if defined on that platform).

And Sys.getenv() to get the value of environmental variables defined on your system, e.g.

#  Path to R home directory
Sys.getenv( "R_HOME" )
#[1] "/Library/Frameworks/R.framework/Resources"

# Path to default R library
Sys.getenv("R_LIBS")
#[1] "~/R64Libs"

To see the available environment variables...

head( names(Sys.getenv()) )
#[1] "__CF_USER_TEXT_ENCODING"    "Apple_PubSub_Socket_Render" "Apple_Ubiquity_Message"    
#[4] "COMMAND_MODE"               "DISPLAY"                    "EDITOR"    

Defining a new environmental variable

To set an environment variable to make it always available to R you need to set that variable in a file called .Renviron which by default is located in your {$HOME} directory. So for instance to make the environment variable R_WORKSPACE available I add the line

R_WORKSPACE = ~/Documents/R/StackOverflow

To /Users/Simon/.Renivron. Then when I load up R you see that path expansion is done automatically...

#  Clean workspace - commented out so you don't wipe your session!
#  rm( list = ls() )

#  See that variable is now available in R
Sys.getenv( "R_WORKSPACE" )
[1] "~/Documents/R/StackOverflow"

See the answer here for a bit more info and options.

Upvotes: 4

Related Questions