将 R data.frame 转换为 Javascript 数组
Convert R data.frame to Javascript array
我想将数据框的某些列保存为特定格式(JavaScript 格式)。我尝试使用 rjson
包中的 toJSON()
但那不起作用。
我的结果应该是这样的:http://leaflet.github.io/Leaflet.markercluster/example/realworld.388.js
最快的方法是使用 apply
函数之一。碰巧我找到的最好的是 apply
本身。
# this will go row by row
apply(allTheData, 1, function(x){
print(x["COL_NAME"])
})
你不能在申请中使用x$COL_NAME
所以你必须使用我上面的方法。
您可以使用其他 apply
函数,但逐行查看我发现这个函数最容易应用。
使用以下脚本解决:
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)
我建议使用专门用于 JSON-R 和 R-JSON 转换的出色且高效的 jsonlite 包:
# 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.: toJSON()
有进一步的参数来控制和微调转换。
我想将数据框的某些列保存为特定格式(JavaScript 格式)。我尝试使用 rjson
包中的 toJSON()
但那不起作用。
我的结果应该是这样的:http://leaflet.github.io/Leaflet.markercluster/example/realworld.388.js
最快的方法是使用 apply
函数之一。碰巧我找到的最好的是 apply
本身。
# this will go row by row
apply(allTheData, 1, function(x){
print(x["COL_NAME"])
})
你不能在申请中使用x$COL_NAME
所以你必须使用我上面的方法。
您可以使用其他 apply
函数,但逐行查看我发现这个函数最容易应用。
使用以下脚本解决:
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)
我建议使用专门用于 JSON-R 和 R-JSON 转换的出色且高效的 jsonlite 包:
# 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.: toJSON()
有进一步的参数来控制和微调转换。