如何从R函数返回输出

时间:2014-08-09 19:58:08

标签: r

我有一个R脚本,它读取csv文件并转换为json输出,这是脚本:

output<-function(myname){
  library(rjson)
  setwd("C:/Rstudio/vCenter")
  ##vcenter <- system.file("instvcenter.csv", package = packageName())
  res <- read.csv("vcenter.csv", header = TRUE, sep = ",")
res$Cpu<-as.numeric(round(res$Cpu, digits=3))
res$Time<-as.numeric(res$Time-14400)

servers <- split(res, res$Host)
dumFun <- function(x){
  sData <- servers[x][[1]]
  if(nrow(sData) >0){
    # create appropriate list
    dumList <- unname(apply(sData[,2:3], 1, function(y) unname(as.list(y))))
    return(toJSON(list(name = x, data = dumList))) 
  }
}       
jsData <- lapply(names(servers), dumFun)
jsInd <- sapply(jsData, is.null)

p<-paste(jsData[!jsInd], collapse = ',')
list(
p<-paste('[', p, ']')
)
return(p)

}

这是读取输出的javascript:

<!DOCTYPE html>
<html>
  <head>
    <title>Hello</title>

    <!-- Include order: first jquery, then opencpu.js, and then your code -->
    <script src="opencpu/jquery-1.10.2.min.js"></script>
    <script src="opencpu/opencpu-0.4.js"></script>
    <script src="opencpu/highcharts.js"></script>
    <script src="opencpu/export-csv.js"></script>

    <script>
    //init this script when the page has loaded
    $(document).ready(function(){
      $("#submitbutton").on("click", function(){
        //disable the button to prevent multiple clicks
        $("#submitbutton").attr("disabled", "disabled");

        var myname = $("#namefield").val();
        //perform the request
        var req = ocpu.rpc("output", {
          myname : myname

        }, function(output){

          //var data=JSON.stringify(output, null, 4);
         //console.log(data);
          //console.log($(this).data("events"));
          //var data=output[0][1];
          //var data =JSON.stringify(output, null, 4);
          //document.write(output);

          //document.write(output[1]);
          //console.log('Error:', output[0][0]);
          //var data = data.replace(/\[1\]/, "");
        $('#output').highcharts({
        //$("#output").highcharts('StockChart',{
        chart: {
            borderColor: '#98AFC7',
                borderRadius: 20,
                borderWidth: 1,
                renderTo: 'output',
                type: 'line',
                marginRight: 10,
                zoomType: 'x',
                resetZoomButton: {
                position: {

                    x: -50,
                    y: -50
                    }
                }
            },
            plotOptions: {
                line: {
                    marker: {
                        radius: 4,
                        lineColor: '#666666',
                        lineWidth: 5
                    }
                }
            },

            exporting: {
            enabled: true
        },
           legend: {
            enabled: true,
            backgroundColor: '#FCFFC5',
            borderColor: 'black',
            borderWidth: 2,
            shadow: true
        },
            rangeSelector: {
                enabled:true               
            },

            scrollbar: {
                    enabled: true
                    },
            navigator : {
                enabled : true
            },
            xAxis: {
        type:'datetime',
                gridLineColor: '#EEEEEE',
                gridLineWidth: 1
            },
            yAxis: { // Primary yAxis
                labels: {

                    style: {
                        color: 'blue'
                    }
                },
                gridLineColor: '#EEEEEE',
                gridLineWidth: 1,

                title: {
                    text: '% CPU Utilization',
                    fontSize: '50px',
                    style: {
                        color: 'blue'
                    }
                }
            },

            credits: {
                enabled: false
            },

            title: {
                text: '% CPU UTILIZATION',
                style: {
                    color: '#333000',
                    fontSize: '14px'
                }
            },


            tooltip: {
            positioner: function(){
                    return{x:20,y:-5};
                },
                pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}<b>',
                valueDecimals: 2
            },

            series: output
    });
});

        //if R returns an error, alert the error message
        req.fail(function(){
          alert("Server error: " + req.responseText);
        });

        //after request complete, re-enable the button 
        req.always(function(){
          $("#submitbutton").removeAttr("disabled")
        });
      });
    });
    </script>

    <style>
      #output{
        height: 600px;
        width: 1500px;
        border: 0px;
        padding: 3px;
      }
    </style>

  </head>

  <body>
    <h1>My First HighStock Chart!!!!</h1>

    <b>Your name: </b> <input type="text" id="namefield">

    <button id="submitbutton" type="button">Submit to server!</button>

    <div id="output"> </div>

    <br />


  </body>
</html>

当我运行这个脚本时,它会给我一个这样的输出:

[1] [ {"name":"rosevengesx02","data":[[1406269800,0.092],[1406271600,0.092]]}]

我试过了:

return(cat(p))

但我知道我远程调用此函数,我得到:

[object Object]

如何在输出中返回函数以便我没有[1]?

1 个答案:

答案 0 :(得分:1)

我很确定抑制[1]的唯一方法是使用cat输出函数返回值。唯一的问题是,即使您将函数分配给变量,例如下面的g <- f(),也会始终打印。

> f <- function() {
      cat(1:10)
  }
> f()
1 2 3 4 5 6 7 8 9 10
> g <- f()   ## still prints, even though I assigned it to a variable
1 2 3 4 5 6 7 8 9 10

如果后者对您来说不是问题,那么这可能就是您的选择。