简体   繁体   中英

Convert R data.frame to Javascript array

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

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM