R等同于Stata本地或全局宏 [英] R equivalent of Stata local or global macros
问题描述
我是一个尝试学习R的Stata用户.
I am a Stata user trying to learn R.
我有几个冗长的文件夹路径,在我的Stata代码中,我将它们存储为本地宏.这两个文件夹中都有多个文件供分析使用.
I have a couple of lengthy folder paths which, in my Stata code, I stored as local macros. I have multiple files in both those folders to use in my analysis.
我知道,在R中,每次我想引用其中一个文件夹中的文件时,都可以更改工作目录,但这绝对不是一个好方法.即使我将文件夹路径作为字符串存储在R中,也无法弄清楚如何引用这些路径.例如,在Stata中,我将使用`folder1'.
I know, in R, I can change the working directory each time I want to refer to a file in one of the folders but it is definitely not a good way to do it. Even if I store the folder paths as strings in R, I can't figure out how to refer to those. For example, in Stata I would use `folder1'.
我想知道是否尝试在R中逐行重新编写Stata代码不是学习R的最佳方法.
I am wondering if trying to re-write Stata code line by line in R is not the best way to learn R.
有人可以帮忙吗?
推荐答案
首先,作为一名前Stata用户,让我推荐 R .在 R中的宏上也有此文章.我认为@Nick Cox是对的,您需要学习以不同的方式做事.但是,像您一样(至少在这种情况下),我经常发现自己已经掌握了如何在Stata中执行此任务并从那里开始的新任务.有时我发现方法是相似的.有时,当采用其他方法更好时,我可以使R像Stata一样工作(例如,循环与矢量化).
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.
在Stata中,通常会这样写:
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"
作为以前的Stata用户,我想在R中做类似的事情.这是我的工作:
As a former Stata user, I want to do something similar in R. Here is what I do:
mydata <- "path to my data directory/"
要导入位于此目录中的csv文件并创建一个名为myfile的数据框,我将使用:
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=""))
或更有效地...
myfile <- read.csv(paste0(mydata, "myfile.csv"))
我不是一个非常高效的R用户,所以也许其他人会看到这种方法的一些缺陷.
I'm not a very efficient R user yet, so maybe others will see some flaws in this approach.
这篇关于R等同于Stata本地或全局宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!