R equivalent of Stata local or global macros

穿精又带淫゛_ 提交于 2019-11-30 14:45:23

First, as a former Stata user, let me recommend R for Stata Users. There is also this article on Macros in R. I think @Nick Cox is right that you need to learn to do things more differently. But like you (at least in this case), I often find myself starting a new task with my prior knowledge of how to do it in Stata and going from there. Sometimes I find the approaches are similar. Sometimes I can make R act like Stata when a different approach would be better (e.g., loops vs. vectorization).

I'm not sure if I will capture your question with the following, but let me try.

In Stata, it would be common to write:

global mydata "path to my data directory/"

To import the data, I would just type:

insheet using "${mydata}myfile.csv"

As a former Stata user, I want to do something similar in R. Here is what I do:

mydata <- "path to my data directory/"

To import a csv file located in this directory and create a data frame called myfile, I would use:

myfile <- read.csv(paste(mydata, "myfile.csv", sep=""))

or more efficiently...

myfile <- read.csv(paste0(mydata, "myfile.csv"))

I'm not a very efficient R user yet, so maybe others will see some flaws in this approach.

Maybe you want file.path()?

a <- "c:"
b <- "users"
c <- "charles"
d <- "desktop"

setwd(file.path(a,b,c,d))
getwd()
#----
[1] "c:/users/charles/desktop"

You can wrap source or read.XXX or whatever else around that to do what you want.

I'm guessing from context that the term "local" when applied to files means that they have been loaded into memory for efficiency purposes? If so, then you need to realize that pretty much all ordinary R objects are handled that way. See ?read.table and ?load. The only way data can remain non-local is to have it reside in a database that has an interface package that supports SQL queries or use specialized packages such as ff or bycol.

Other than that and Chase's idea to use file.path(), any reference to files or connections is done using the proper read/load/scan functions to which character values are given as (variously named) arguments. You can see a variety of low-level functions with ?file and perhaps following some of the additional links from that help page. You could store one or more results of a file.path construction in a character vector which could be named for easy reference.

 pathvecs <- c(User= "~/", hrtg="~/Documents/Heritage/")
 pathvecs
#                   User                    hrtg 
#                   "~/" "~/Documents/Heritage/" 
pathvecs["hrtg"]
#                   hrtg 
#"~/Documents/Heritage/" 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!