Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Solution 2:

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.


Solution 3:

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)

Post a Comment for "Convert R Data.frame To Javascript Array"