简体   繁体   中英

run an r script from within an r script and change some values

I have an R script that I would like to run to import some data. The R script is called load_in_year1-4 . I have designed this script so that I only have to make 3 changes to the code at the top and everything will run and import the correct data files.

The 3 changes are;

year <- "Year4"
weeks <- "1270_1321"
product <- "/cookies"

However I have 20 years worth of data and more than 50 products.

I am currently manually changing the top of each file and running it, so I have no errors currently in the data.

What I would like to do is to create a separate R script which will run the current script.

I would like to have something like

year <- c("year1", "year2", "year3"....)
weeks <- c("1270_1321", "1321_1327"....)
product <- c("product1", "product2"....)

So it will take year 1, week 1270_1321 and product1, call them year , week , product and run the R script which I have created.

Is there a grid function anybody can suggest?

EDIT: I have something like the following

#Make changes here
year <- "Year11"
weeks <- "1635_1686"
product <- "/cigets"

# year1: "1114_1165", year2: "1166_1217", year3: "1218_1269"


#Does not need changing
files <- gsub("Year1", as.character(year), "E:/DATA/Dataset/Year1")

parsedstub <- "E:/DATA/Dataset/files/"
produc <- paste0("prod", gsub("/", "_", as.character(product)))

drug <- "_drug_"
groc <- "_groc_"

####################Reading in the data###########################################

drug <- read.table(paste0(files, product, product, drug, weeks), header = TRUE)
groc <- read.table(paste0(files, product, product, groc, weeks), header = TRUE)

To make a function out of your script, do something like this:

get.tables <- function(year,weeks,product){
  files <- gsub("Year1", as.character(year), "E:/DATA/Dataset/Year1")
  parsedstub <- "E:/DATA/Dataset/files/"
  product <- paste0("prod", gsub("/", "_", as.character(product)))
  drug <- "_drug_"
  groc <- "_groc_"
  ####################Reading in the data###########################################
  drug <- read.table(paste0(files, product, product, drug, weeks), header = TRUE)
  groc <- read.table(paste0(files, product, product, groc, weeks), header = TRUE)
  list(drug = drug, groc = groc)
}

Then you could use something in the apply family to apply this function to different years, weeks, and products.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM