R macros to enable user defined input similar to %

2019-06-14 08:58发布

问题:

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")

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

and replace the code as

`C:/Projects/Consumption curves/UKPOV/excel files/&metric_product_CC_2009_salespercap.csv`

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.

I am looking for something similar in R however.

回答1:

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)

or wrapped in a function

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(....)) will work

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

For your particular case you can replace txt with the same paste0 logic to build your variable names.

Full explanation in this SO Q/A

Hope it helps