R中的批处理文件中的setwd()

时间:2018-10-23 14:33:58

标签: r batch-file command-line automation

我想从批处理文件运行R脚本以自动化相同的过程,并希望在批处理文件中设置工作目录。

R脚本

<script>
        $(function () {
            debugger
            var customVal = $('#subtab-agent-home-unpaid').find('span.badge ').text();
            var CellCount = $('#sessionDivCount').attr('data-id');
            var headercount = '1';
            var displayCount = Number(CellCount) + Number(headercount);


            var shouldPopulateHeader = '';
            var dataSource = new kendo.data.DataSource({
                transport: {
                    read: onRead,
                    submit: onSubmit
                },
                requestEnd: function (e) {
                    setTimeout(function (e) {
                        debugger
                        if (shouldPopulateHeader) {
                            shouldPopulateHeader = false;

                            var spreadsheet = $("#spreadsheet").data("kendoSpreadsheet");
                            var sheet = spreadsheet.activeSheet();
                            // Change the default headers for the first and the second column
                            sheet.batch(function () {
                                sheet.range("A1").value("Order ID");
                                sheet.range("A1").addClass("customHeaderRowStyles");
                                sheet.range("B1").value("PO Number");
                                sheet.range("C1").value("Method");
                                sheet.range("D1").value("Check/Receipt/Reference/Confirmation Number");
                                sheet.range("E1").value("Date Check Was Made Made Payment Was Made");
                                sheet.range("F1").value("Agent Payment Confirmation");
                                sheet.range("G1").value("Estimated Payment Arrival Date");

                                sheet.range("A1:A16384 ").enable(false);

                                sheet.range("B1:B16384 ").enable(false);
                                sheet.range("A2:A16384 ").textAlign = "center";

                                var range = sheet.range("A2:A16384"); // 2x2 cell range
                                range.bold = true;
                                range.textAlign = "center";
                                range.color("green");

                                var range1 = sheet.range("B2:B16384"); // 2x2 cell range
                                range1.bold = true;
                                range1
                                range1.textAlign = "center";
                                range1.color("black");
                                range1.defaultValue = null;
                                sheet.range("c2").textAlign = "center";
                            }, { recalc: true });
                        }
                    }, 0);
                },
                batch: true,
                change: function () {
                    $("#cancel, #save").toggleClass("k-state-disabled", !this.hasChanges());
                },
                schema: {
                    model: {
                        //id: "ProductID",
                        fields: {
                            OrderID: {
                                type: "number",
                                defaultValue: null
                            },
                            PO: {
                                type: "string",
                                defaultValue: null
                            },
                            Method: {
                                type: "string",

                            },
                            Check_Receipt_Refernce_confirmation_Number: {
                                type: "string"

                            },
                            DateCheck_Was_Mailed_Payment_Was_Made: {
                                type: "date"
                            },
                            Agent_Payment_Confirmation: {
                                type: "string"
                            },
                            Estimated_Payment_Arrival_Date: {
                                type: "date"
                            },

                        }
                    }
                }
            });

            $("#spreadsheet").kendoSpreadsheet({
                columns: 8,
                rows: displayCount,
                toolbar: true,
                sheetsbar: false,
                sheets: [{
                    name: "Products",
                    dataSource: dataSource,
                    filter: {
                        ref: "A1:G"+Number(CellCount)+"",
                        columns:[]
                    },
                    rows: [{
                        height: 20,
                        cells: [
                            {
                                value: "Order ID",
                                bold: "true",
                                background: "#9c27b0",
                                textAlign: "center",
                                color: "white",
                                hidden: true,
                                enable: false
                            }, {
                                bold: "true",
                                background: "#9c27b0",
                                textAlign: "center",
                                color: "white",
                                enable: false
                            }, {
                                bold: "true",
                                background: "#9c27b0",
                                textAlign: "center",
                                color: "white",

                            }, {
                                bold: "true",
                                background: "#9c27b0",
                                textAlign: "center",
                                color: "white",

                            },
                            {
                                bold: "true",
                                background: "#9c27b0",
                                color: "white",
                                textAlign: "center",

                            },
                            {
                                bold: "true",
                                background: "#9c27b0",
                                textAlign: "center",
                                color: "white"
                            }, {
                                bold: "true",
                                background: "#9c27b0",
                                textAlign: "center",
                                color: "white"
                            }
                        ]
                    }],
                    columns: [
                        { width: 145 },
                        { width: 145 },
                        { width: 145 },
                        { width: 300 },
                        { width: 300 },
                        { width: 300 },
                        { width: 300 }
                    ]
                }]
            });



            function onSubmit(e) {
                debugger
                var arrofId = new Array();
                var models = {};
                var obj = "";
                for (i = 0; i < JSON.stringify(e.data.created.length); i++) {
                    obj = e.data.created[i];
                    arrofId.push(obj);
                }
                arrofId.push(obj);
                $.ajax({
                    type: "POST",
                    url: "../Agent/GetDataSpreadSheetSubmit",
                    data: '{models: ' + JSON.stringify(arrofId) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        alert('Record Saved Succesfully');
                        $('#grid').data('kendoGrid').dataSource.read();
                        $('#grid').data('kendoGrid').refresh();
                    },
                    error: function (xhr, httpStatusMessage, customErrorMessage) {
                        alert(xhr.responseText);
                    }
                });
            }

            function onRead(options) {
                $.ajax({
                    url: "../Agent/GetDataSpreadSheet",
                    dataType: "json",
                    success: function (result) {
                        debugger
                        options.success(result.data);
                        $("#spreadsheet").data("kendoSpreadsheet").refresh();
                        var spreadsheet = $("#spreadsheet").data("kendoSpreadsheet");
                        var sheet = spreadsheet.activeSheet();


                        sheet.range("A1").value("Order ID");

                        sheet.range("B1").value("PO Number");
                        sheet.range("C1").value("Method");
                        sheet.range("D1").value("Check/Receipt/Reference/Confirmation Number");
                        sheet.range("E1").value("Date Check Was Mailed Payment Was Made");
                        sheet.range("F1").value("Agent Payment Confirmation");
                        sheet.range("G1").value("Estimated Payment Arrival Date");
                        sheet.range("A1:A16384 ").enable(false);
                        sheet.range("A1:A16384 ").textAlign("center");
                        sheet.range("B1:B16384 ").enable(false);
                        sheet.range("B1:B16384 ").textAlign("center");
                        sheet.range("C1:C16384 ").textAlign("center");
                        sheet.range("D1:D16384 ").textAlign("center");
                        sheet.range("E1:E16384 ").textAlign("center");
                        sheet.range("F1:F16384 ").textAlign("center");
                        sheet.range("G1:G16384 ").textAlign("center");
                        sheet.range("A2:A16384 ").textAlign = "center";

                        var range = sheet.range("A2:A16384"); // 2x2 cell range
                        range.bold = true;
                        range.textAlign = "center";
                        range.color("black");

                        var range1 = sheet.range("B2:B16384"); // 2x2 cell range
                        range1.bold = true;

                        range1.textAlign = "center";
                        range1.color("black");
                        range1.defaultValue = null;
                        sheet.range("c2").textAlign = "center";



                    },
                    error: function (result) {
                        options.error(result);
                    }
                });
            }

            $("#save").click(function () {
                if (!$(this).hasClass("k-state-disabled")) {
                    dataSource.sync();
                }
            });

            $("#cancel").click(function () {
                if (!$(this).hasClass("k-state-disabled")) {
                    dataSource.cancelChanges();
                }
            });
            $("#btncloseSpreadheet").click(function () {
               $('#ExportExcelModel').toggle();

            });






        });

</script>

批处理文件

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)

}

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以将commandArgs()Rscript一起使用,以轻松获得所需的行为。考虑以下我称为so-answer.R的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"

this blog post上可以找到关于commandArgs()的很好的解释。

如果您真的不习惯使用R CMD BATCH,请看看this blog post并尝试以下操作:

# 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 

答案 1 :(得分:0)

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