Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

Joining character and numeric json elements in R

I am trying to join two json objects into a single json object in R using jsonlite.

As a simple illustration, if I have the following:

The api that I am using needs a Json object that has the column names of a dataframe as the first element, followed by the numeric output of the rows. To illustrate:

df <- data.frame(A = rnorm(2), B = rnorm(2), C = rnorm(2))

Which I need to look like:

set.seed(123)

[["A", "B", "C"], [-0.5605,1.5587,0.1293],[-0.2302,0.0705,1.7151]]

But the following attempts fail at achieving the above:

c( jsonlite::toJSON( names(df) ), jsonlite::toJSON( df, "values" ))
paste0( jsonlite::toJSON( names(df) ), jsonlite::toJSON( df, "values" ))

This solution does not work, and I haven't found any other suggestions for how to achieve this.

Any ideas would be appreciated.

question from:https://stackoverflow.com/questions/65908075/joining-character-and-numeric-json-elements-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An option is to split by row (asplit with MARGIN = 1) into a list, concatenate (c) with the names of the data and apply the toJSON

library(jsonlite)
toJSON(c(list(names(df)), asplit(df, 1)))
#[["A","B","C"],[-0.5605,1.5587,0.1293],[-0.2302,0.0705,1.7151]] 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...