user1471980
user1471980

Reputation: 10656

How do you parse out output in R and read files in R package

I have this function to read data from .csv file and output the result as json format:

My vcenter.csv file looks like this:

Host       Time    Cpu
server1 1406284200 0.0920
server1 1406286000 0.0920
server1 1406287800 0.0912
server1 1406289600 0.0928
server1 1406291400 0.0912
server1 1406293200 0.0904

output<-function(myname){
  library(rjson)
res<-read.csv("vcenter.csv", header=T, sep=',')

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 = ',')
p<-paste('[', p, ']')
print(p)
}

a. When I call this function remotely I get something like this:

[1] "[ {\"name\":\"server1\",\"data\":[[1406284200,0.387200012]

Is it possible to not display [1] and \ values in the output?

b.When I build this code with RStudio as a package with vcenter.csv file and install the package, when I run the output.R function, it does not see the vcenter.csv file. Where should I put the vcenter.csv? I tried putting it in the library directory, the same directory as the output.r script, not luck. I keep getting file(file, "rt") connection error. Any ideas?

Upvotes: 0

Views: 581

Answers (1)

Gabor Csardi
Gabor Csardi

Reputation: 10826

  1. As Dirk said, use cat() instead of print().

  2. Put the file in the inst directory. If it is a data file, then a place people often use is inst/extdata. See http://cran.r-project.org/doc/manuals/r-devel/R-exts.html#Data-in-packages

    Then, in the installed package, you can find the data file like this:

    vcenter <- system.file("inst/extdata/vcenter.csv", package = packageName())
    res <- read.csv(vcenter, header = TRUE, sep = ",")
    ...
    

    Note that you don't have to parse the file in your package, you can also include it as an Rdata file, see the Writing R extensions link above.

Upvotes: 1

Related Questions