3

I want to save some columns of my data frame into a specific format (JavaScript format). I've tried to use toJSON() from rjson package but that doesn't work.

My result should looks like : http://leaflet.github.io/Leaflet.markercluster/example/realworld.388.js

1
  • 1
    Show your code - what you've tried, and a sample of the data, please. And explain what you mean when you say the rjson package "doesn't work". Apr 8, 2016 at 15:20

3 Answers 3

8

I propose using the awesome and performant jsonlite package which is specialized in JSON-R and R-JSON conversion:

# load package 
library(jsonlite)

# get help
?toJSON

# do transformations
df <- data.frame(a=1:3, b=letters[1:3])

toJSON(df)
## [{"a":1,"b":"a"},{"a":2,"b":"b"},{"a":3,"b":"c"}] 

toJSON(df, dataframe="rows")
## [{"a":1,"b":"a"},{"a":2,"b":"b"},{"a":3,"b":"c"}] 

toJSON(df, dataframe="columns")
## {"a":[1,2,3],"b":["a","b","c"]} 

toJSON(df, dataframe="values")
## [[1,"a"],[2,"b"],[3,"c"]] 

PS.: The toJSON() has further arguments to control and fine tune conversion.

1

The fastest way to do it is going to use one of the apply functions. It just so happens the best one I found was apply itself.

# this will go row by row
apply(allTheData, 1, function(x){
    print(x["COL_NAME"])
})

You can't use x$COL_NAME in apply so you have to use the way I did above.

You could use other apply functions, but to go row by row I found this one the easiest to apply.

1

Solved by using the following script :

datasetres <- idw.output[,1:3]
write("var addressPoints = [",file="Data/output.txt")
for(i in 1:nrow(datasetres)){
  write(paste("[",datasetres[i,]$lat,",", datasetres[i,]$lon,", \"", datasetres[i,]$var1.pred, "\" ],",sep=''),file="Data/output.txt",append=TRUE)
}
write("];",file="Data/output.txt",append = TRUE)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.