如何在R语言中展现用户和环境变量? [英] How to unfold user and environment variable in R language?
问题描述
例如,在Python中,您可以通过写出以下代码来获取它:
有没有办法在R中扩展波浪符号和环境变量?
import os
os.path.expanduser(〜/ r_workspace)#return/ Users / yourname / r_workspace(在OS X中)
os.path.expandvars($ R)#return/ Users / yourname / r_workspace,如果您提前设置$ R
R是否提供了这种功能?我不喜欢写下面的代码:
read.csv(/ Users / myname / python_workspace / subdirectory_1 /subdirectory_2/data.csv)
相同!
path.expand(〜)
#[1]/ Users / Simon
path.expand
将通过替换用户主目录(如果在该平台上定义)的主要波浪号。
和 Sys.getenv()
获取系统中定义的环境变量的值,例如
#R主目录的路径
Sys.getenv (R_HOME)
#[1]/Library/Frameworks/R.framework/Resources
#默认路径R库
Sys.getenv(R_LIBS )
#[1]〜/ R64Libs
查看可用的环境变量。 ..
$ b
head(names(Sys.getenv()))
#[1]__CF_USER_TEX $ _
$ b $$$$$$ b 定义新的环境变量
要设置环境变量以使其始终可用于R,您需要将该变量设置为名为 .Renviron
默认情况下,它位于您的 {$ HOME}
目录中。因此,例如要使环境变量 R_WORKSPACE
可用添加行
R_WORKSPACE =〜/ Documents / R / StackOverflow
至 / Users / Simon /.Renivron
。然后当我加载R时,您会看到路径扩展自动完成...
#清洁工作区 - 注释掉,所以你不要擦你的会话!
#rm(list = ls())
#看到这个变量现在可以在R
Sys.getenv(R_WORKSPACE)
[1] 〜/ Documents / R / StackOverflow
请参阅回答这里了解更多信息和选项。
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")
解决方案 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.
这篇关于如何在R语言中展现用户和环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!