R宏可启用类似于SAS中的%let的用户定义输入 [英] R macros to enable user defined input similar to %let in SAS
问题描述
我正在尝试使R中的特定过程自动化,在该过程中,代码基本上保持不变,但是导入的输入文件会更改-路径和大多数文件名都是相同的,只是一个单词发生了更改-某些变量名发生了更改. 我想进行用户定义的这些更改:非常类似于SAS中的%let.我可以在其中用&.
I am trying to automate a particular process in R, where essentially the code remains the same but the input files imported change- the path and most of the file name is the same only one word changes- and certain variable names change. I would like to make these changes user defined: much like %let in SAS. where i can call a value with &.
例如,如果我有此特定的导入代码:
For example if i have this particular import code:
Category_sales<- read.csv("C:/Projects/Consumption curves/UKPOV/excel files/MSP_product_CC_2009_salespercap.csv")
我只希望MSP一词根据用户的需要进行更改. 在SAS中,我将定义一个宏变量,例如%let metric = MSP
Where I would like only the word MSP to change depending on what the user wants. In SAS I would define a macrovariable like say %let metric=MSP
并将代码替换为
`C:/Projects/Consumption curves/UKPOV/excel files/&metric_product_CC_2009_salespercap.csv`
如果我有一个变量,请说 MaxGNI ,并且我只希望用户定义/替换GNI部件,如 Max& econvar ,在该位置我可以拥有 econvar 定义为%let econvar = GNI 或其他任何指标.
Also If I have a variable say MaxGNI and I would like only the GNI part to be user defined/replaced like Max&econvar where I could have econvar defined as %let econvar= GNI or any other metric.
但是我正在寻找R中类似的东西.
I am looking for something similar in R however.
推荐答案
您可以使用paste0
函数来完成此任务.
You can accomplish this task using the paste0
function.
metric <- "MSP"
infile <- paste0("C:/Projects/Consumption curves/UKPOV/excel files/",metric,"_product_CC_2009_salespercap.csv")
Category_sales <- read.csv(infile)
或包装在函数中
readCSV <- function(var) {
metric <- var
infile <- paste0("C:/Projects/Consumption curves/UKPOV/excel files/",metric,"_product_CC_2009_salespercap.csv")
return(infile)
}
Category_sales <- read.csv(readCSV('MSP'))
您可以对字符串中需要替换的所有位应用相同的逻辑.
You can apply the same logic to all the bits that need to be replaced in your string.
关于变量名称,您可以执行以下操作:
Regarding to variable names you can do:
eval(parse(....))
将起作用
data1 <- data.frame(column1 = 1:10, column2 = letters[1:10])
txt <- "data1$column2"
> eval(parse(text = txt))
[1] a b c d e f g h i j
Levels: a b c d e f g h i j
对于您的特殊情况,您可以用相同的paste0
逻辑替换txt
来构建变量名.
For your particular case you can replace txt
with the same paste0
logic to build your variable names.
希望有帮助
这篇关于R宏可启用类似于SAS中的%let的用户定义输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!