setwd () из командного файла в R - PullRequest
0 голосов
/ 23 октября 2018

Я хочу запустить R-скрипт из командного файла для автоматизации того же процесса и хочу установить рабочий каталог в командном файле.

R скрипт

files <- list.files(pattern=*.csv", full.names=TRUE, 
recursive=FALSE)

lapply(files, function(x) {

  df <- read.csv(x, header = TRUE, sep = ",")

 inds <- which(df$pc_no == "DELL")
 df[inds - 1, c("event_rep", "loc_id")] <- df[inds, c("pc_no", "cust_id")]
 df1 <- df[-inds, ]

 write.csv(df1, paste0('cleaned_', x), row.names = FALSE)

}

ФАЙЛ ПАКЕТА

"C:\R\R-3.5.1\bin\i386\R.exe" CMD BATCH 
"C:\folder\myscript.R" -e setwd("C:\Documents") 
"C:\folder\test.Rout"

Как я могу это сделать?

Ответы [ 2 ]

0 голосов
/ 23 октября 2018

В Windows:

"C:\Program Files\R\R-3.5.1\bin\i386\Rscript.exe" -e "setwd('C:\\Users\\saeid\\Documents');source('myscript.R')" > "C:\Users\saeid\Documents\test.Rout"

и myscript.R:

print(getwd())

test.Rout содержимого:

[1] "C:/Users/saeid/Documents"
0 голосов
/ 23 октября 2018

Вы можете использовать commandArgs() с Rscript, чтобы легко получить желаемое поведение.Рассмотрим следующий R-скрипт, который я назвал so-answer.R:

# First get the argument giving the desired working directory:
wd <- commandArgs(trailingOnly = TRUE)
# Then check if we can correctly set the working directory:
setwd(wd)
getwd()

Затем мы можем запустить его из командной строки, передав в качестве аргумента каталог, который нам нужен:

duckmayr@duckmayr-laptop:~$ Rscript so-answer.R Documents
[1] "/home/duckmayr/Documents"

Хорошее, доступное объяснение commandArgs() можно найти по адресу в этом блоге .

Если вы действительно устали от использования R CMD BATCH, взгляните на thisсообщение в блоге и попробуйте что-то вроде следующего:

# First get the argument giving the desired working directory:
eval(parse(text = commandArgs(trailingOnly = TRUE)[1]))
# Then check if we can correctly set the working directory:
setwd(wd)
getwd()

, который вы можете запустить из командной строки, например

duckmayr@duckmayr-laptop:~$ R CMD BATCH '--args wd="Documents"' so-answer.R so-answer.Rout

, что приводит к таким выводам

duckmayr@duckmayr-laptop:~$ cat so-answer.Rout

R version 3.5.1 (2018-07-02) -- "Feather Spray"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> # First get the argument giving the desired working directory:
> eval(parse(text = commandArgs(trailingOnly = TRUE)[1]))
> # Then check if we can correctly set the working directory:
> setwd(wd)
> getwd()
[1] "/home/duckmayr/Documents"
> 
> proc.time()
   user  system elapsed 
  0.478   0.052   0.495 
...