在某些约束下将R中的矩阵/数据帧转换为JSON对象 [英] Converting a matrix/dataframe in R to JSON object with some constraints

查看:155
本文介绍了在某些约束下将R中的矩阵/数据帧转换为JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已删除:

我必须将R中的矩阵转换为其中具有某些结构的JSON对象.我正在使用rjson包.通过一个例子,让我说明一下我想要的.我的具体情况是R中推荐系统代码的输出,其中X2 X3是最接近特定项目X1的2个项目.而且,X4,X5是与该行的(X1,X2)和(X1,X3)相关的相似性得分.我希望将每个项目的所有推荐项目都作为JSON对象,并将每个项目连同其推荐的JSON对象一起作为更大的JSON对象.分数也应纳入JSON结构中.

I have to convert a matrix in R to a JSON object with some structure in it. I am using the rjson package. Through an example, let me illustrate what I want. My specific case is the output of a recommender system code in R where the X2 X3 are the 2 closest items to a particular item X1. Also, X4,X5 are the scores of similarity associated with (X1,X2) and (X1,X3) for that row. I want all the recommended items for every item as JSON objects and every item along with its recommended JSON object- items as a bigger JSON objects.The scores should also be incorporated into the JSON structure.

让我通过一个例子来解释.

Let me explain through a example.

假设我有一个矩阵

X1 X2 X3 X4 X5 
1 22 23  0.8 0.5
34 4 87  0.4 0.4
23 7 92  0.6 0.5

我想要每个项目(每行每个X1)的JSON结构,以及推荐的项目和每个组合的相似性得分(作为单独的JSON实体),并按顺序进行.我不希望包含这些单个对象的整个JSON对象. 假设还有一个称为"coid"的实体将作为代码的输入给出.我假设它是XYZ,并且所有行都相同.

I want a JSON structure for every item (every X1 for every row) along with the recommended items and the similarity scores for each combination as a separate JSON entity and this being done in sequence. I don't want an entire JSON object containing these individual ones. Assume there is one more entity called "coid" that will be given as input to the code. I assume it is XYZ and it is same for all the rows.

{ "_id" : { "coid" : "XYZ", "iid" : "1"}, "items" : [ { "item" : "22", "score" : 0.8},{ "item": "23", "score" : 0.5}] }
{ "_id" : { "coid" : "XYZ", "iid" : "34"},"items" : [ { "item" : "4", "score" : 0.4},{ "item": "87", "score" : 0.4}] }
{ "_id" : { "coid" : "XYZ", "iid" : "23"},"items" : [ { "item" : "7", "score" : 0.6},{ "item": "92", "score" : 0.5}] }

如上所述,每个实体都是有效的JSON结构/对象,但它们没有作为一个整体放在一个单独的JSON对象中.

As in the above, each entity is a valid JSON structure/object but they are not put together into a separate JSON object as a whole.

我感谢为上一个问题所做的所有帮助,但不知何故,我觉得这里的新更改与它们无关,因为最后,如果您执行toJSON(某些实体),则它将整个内容转换为一个JSON对象.我不要 我希望将像这样的单个文件写入文件.

I appreciate all the help done for the previous question but somehow I feel this new alteration I have here is not related to them because in the end, if you do a toJSON(some entity), then it converts the entire thing to one JSON object. I don't want that. I want individual ones like these to be written to a file.

对于我的无知和不便,我深感抱歉.请帮忙. 谢谢.

I am very sorry for my ignorance and inconvenience. Please help. Thanks.

推荐答案

首先,您的json无效.您可以在这里上查看其有效性.

First of all, your json is not valid. You can check the validity for example here.

话虽如此,要获得类似于所需的json输出的内容,您可以将其作为f

That being said, to get something similar to your desired json output, you can do as f

library(RJSONIO)

# recreating your matrix
m <- matrix(c(1,22,23,34,4,87,23,7,92),nrow=3,byrow=T)
colnames(m)<-c('X1','X2','X3')

# convert numeric matrix to character (if necessary)
m <- matrix(as.character(m),nrow=nrow(m))

# transform your matrix before turning into json    
p <- apply(m,MARGIN=1,FUN=function(r)list(Item=unname(r[1]),Recos=unname(r[-1])))

# jsonize
toJSON(p)

结果:

[
    {
        "Item" : "1",
        "Recos" : ["22", "23"]
    },
    {
        "Item" : "34",
        "Recos" : ["4", "87"]
    },
    {
        "Item" : "23",
        "Recos" : ["7", "92"]
    }
]


编辑(根据您的编辑):

library(RJSONIO)

# recreating your matrix
m <- matrix(c(1,22,23,34,4,87,23,7,92),nrow=3,byrow=T)
colnames(m)<-c('X1','X2','X3')

# transform your matrix before turning into json    
p <- apply(m,MARGIN=1,
           FUN=function(r){
             list(itemID=unname(r[1]),
                  recommendedItems=lapply(unname(r[-1]),
                                          FUN=function(i)list(itemID=i)))
           })

# jsonize
toJSON(p)

结果:

[{
        "itemID" : 1,
        "recommendedItems" : [{
                "itemID" : 22
            }, {
                "itemID" : 23
            }
        ]
    }, {
        "itemID" : 34,
        "recommendedItems" : [{
                "itemID" : 4
            }, {
                "itemID" : 87
            }
        ]
    }, {
        "itemID" : 23,
        "recommendedItems" : [{
                "itemID" : 7
            }, {
                "itemID" : 92
            }
        ]
    }
]


我宁愿尝试解释如何通过RJSONIO包将R结构转换为json,而不是为您编写代码.

Instead of writing the code for you, I'd rather try to explain how an R structure is turned into a json by RJSONIO package.

就json转换而言,我考虑了3种种类"的对象:

As far as json conversion is concerned, I consider 3 "kind" of objects:

  1. 未命名列表(或矢量)
  2. 命名列表(或向量)
  3. 一个元素的向量

1):元素(例如v <- list('a','b','c'))的未命名列表(或向量)将转换为json:

1) An unnamed list (or vector) of elements (e.g. v <- list('a','b','c')), is translated to json as:

[ element_1, element_2, element_3, ... ]

,其中element_n是列表的第n个元素.当然,列表中的每个元素都可以是另一个复杂对象,按照我在此描述的3条规则,该对象将变成json.

with element_n being the n-th element of the list. Of course each element of the list can be, in turn, another complex object that is turned into json following the 3 rules I am describing here.

2),一个命名列表(或向量)(例如n <- list(A="foo",B="bar"))被转换为json:

2) A named list (or vector) (e.g. n <- list(A="foo",B="bar")), is translated to json as:

{ "name_1": value_1, "name_2": value_2, ...  }

,其中name_n是命名列表的第n个元素的名称,而value_1是命名列表的第n个元素的值.当然,命名列表的每个值都可以是另一个复杂对象,按照我在此描述的3条规则,该对象将变成json.

with name_n being the name of the n-th element of the named list, and value_1 the value of the n-th element of the named list. Of course each value of the named list can be, in turn, another complex object that is turned into json following the 3 rules I am describing here.

3)正如您可以正确指出的那样,R中的每个对象都是一个向量.连a <- 1都是一个元素的数字向量.因此,遵循前面的2条规则,您希望例如将list(x=1)转换为{ "x" : [ 1 ] }.但是由于toJSON函数的参数asIs(默认为FALSE),单个元素的矢量(未列出)被视为标量.

3) As you could correctly point out, every object in R is a vector. Even a <- 1 is a numeric vector of one element. So, following the previous 2 rules, you would expect for example list(x=1) to be translated as { "x" : [ 1 ] }. But thanks to parameter asIs (FALSE by default) of toJSON function, vectors (not lists) of single elements are considered scalars.

话虽这么说,下面是一些例子:

That being said, here follows some examples:

toJSON(list(list(A=2),1:3))
> '[ { "A": 2 }, [ 1, 2, 3 ] ]'

toJSON(list(A=list(1),B=list(C="X"),D=1))
> '{ "A": [ 1 ], "B": { "C": "X" }, "D": 1 }'

这篇关于在某些约束下将R中的矩阵/数据帧转换为JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆