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
对于您的特定情况,您可以将 txt
替换为相同的 paste0
逻辑来构建变量名称.
For your particular case you can replace txt
with the same paste0
logic to build your variable names.
希望对你有帮助
这篇关于R 宏以启用类似于 SAS 中的 %let 的用户定义输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!