R equivalent of local or global macro Stata

I am a Stata user trying to learn R. I have several long paths to folders that are stored as local in my Stata code. I have several files in both folders for use in my analysis. I know that in R I can change the working directory every time I want to link to a file in one of the folders, but this is definitely not a good way to do this. Even if I save the folder paths as strings in R, I cannot figure out how to access them (for example, using `folder1 'in Stata). I am wondering if trying to rewrite Stata code line by line in R is not the best way to find out R. Can someone help?

+5
source share
3 answers

First, as a former Stata user, let me recommend R for Stata users . There is also an article about macros in the R . I think @Nick Cox is right that you need to learn how to do things differently. But, like you (at least in this case), I often start a new task with my prior knowledge of how to do this in Stata and from there. Sometimes I find approaches similar. Sometimes I can get R to act like Stata when another approach is better (e.g. loops versus vectorization ).

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

In Stata, it would usually write:

global mydata "path to my data directory/"

To import the data, I would simply type:

insheet using "${mydata}myfile.csv"

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

mydata <- "path to my data directory/"

csv, , myfile, :

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

...

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

R, , , .

+6

, file.path()?

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

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

source read.XXX - , , .

+5

, "" , ? , , R . . ?read.table ?load. , , , , , SQL- , ff bycol.

In addition, and Chase’s idea of ​​using file.path (), any link to files or connections is made using the correct read / download / scan functions, whose values ​​are assigned as (differently named) arguments. You can see a lot of low-level functions with ?fileand, perhaps, after some additional links on this help page. You can save one or more construction results file.pathin a character vector, which could be called for convenience.

 pathvecs <- c(User= "~/", hrtg="~/Documents/Heritage/")
 pathvecs
#                   User                    hrtg 
#                   "~/" "~/Documents/Heritage/" 
pathvecs["hrtg"]
#                   hrtg 
#"~/Documents/Heritage/" 
+1
source

All Articles