0

I have an R script that reads a csv file and converts to json ouput, here is the script:

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)

}

this is the javascript that reads the output:

<!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>

When I run this script, it gives me an ouput like this:

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

I tried:

return(cat(p))

but wen I call this function remotely, I get:

[object Object]

How would I return the function so that I dont have [1], in the output?

13
  • @RichardScriven, that did not work. I still get [1] at the output. Commented Aug 10, 2014 at 3:30
  • Can you define what "remotely" means? Commented Aug 10, 2014 at 6:34
  • @RomanLuštrik, I execute a function remotely and I get a json formated data. I verified that I get the data to the front end by doing document.write(output). When I pass that data to highcharts series object, I don't see the lines. I do however see the chart border, title but no data on the chart. I am at a loss, cannot seem to find an answer. Commented Aug 11, 2014 at 1:47
  • Have you tried to use return(cat(p)[0]) ? Commented Aug 11, 2014 at 10:52
  • @SebastianBochan, return(cat(p)[0] does not work. On the front end, when I do this cosole.log(ouput), I get object{} Commented Aug 11, 2014 at 11:19

1 Answer 1

1

I'm fairly certain that the only way to suppress the [1] is to output the function return value with cat. The only issue with this is that even if you assign your function to a variable, say g <- f() below, it will always print.

> 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

If the latter isn't a problem for you, then this might be the way to go.

Sign up to request clarification or add additional context in comments.

6 Comments

when I run the function locally, I dont get the [1]. But when I call this function remotely via ajax call, I get [object object], no data. I am not sure what is going on here.
It literally says "object object" ?
when I do document.write(output of the function), I get [object Object]
When I use print(p), I see the data on document.write, I dont get what's happening here.
Neither do I . It sounds like a dispatch issue. Have you tried running a little sample script (like one line of code) and see if that works remotely?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.