1

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.

user36176
  • 339
  • 1
  • 2
  • 11
  • 1
    Maybe `file.choose()`, or use `metric <- "MSP"`, then use `myCSV <- paste("C:/x/y/", metric, "blabla.csv")` to create a path to the file, then use `Category_sales <- read.csv(myCSV)`. – zx8754 Jul 14 '16 at 06:52

1 Answers1

2

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

Community
  • 1
  • 1
Altons
  • 1,422
  • 3
  • 12
  • 23
  • The first solution is great. However I also wanted to know if this is possible for variables like say. Min_max_Ratio_smoothGNI <-MaxGNIPPP_smooth/MinGNIPPP_smooth where I want GNIPPP to be replaced with another string which is user defined – user36176 Jul 14 '16 at 07:18
  • how are you planning to use those variables? reporting? modelling? you can follow the same logic – Altons Jul 14 '16 at 07:28
  • I have expanded my answer to cover the 2nd part of your original question – Altons Jul 14 '16 at 07:36