Convert R data.frame to Javascript array
Asked Answered
G

3

5

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

Gasconade answered 8/4, 2016 at 15:17 Comment(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".Assumptive
S
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.

Sadden answered 8/4, 2016 at 15:33 Comment(0)
E
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.

Enlace answered 20/12, 2016 at 20:59 Comment(0)
S
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.

Sadden answered 8/4, 2016 at 15:33 Comment(0)
G
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)
Gasconade answered 8/4, 2016 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.