2016-07-14 81 views
-1

df变化数据帧到在JSON特定格式文件

该链接是,我有R中的数据帧的屏幕截图和我有困难它与这种格式转移到JSON文件:

{"id2": 1, "x": [0,0,0,0,0,1,0]} 
{"id2": 1, "x": [0,0,1,0,0,1,1]} 

等等......

我一直在尝试使用R中的tojson()功能以及一些其他的事情,我在网上找到,但似乎没有奏效。任何关于此的指导都会非常有帮助。总共有47列和10000行,因此手动执行操作可能需要一段时间。

+0

请'输入'您的数据的一部分,不要链接到数据...尤其是如果这些链接与图片... – SabDeM

回答

1

下面是一个示例,使用与您的样本数据框类似的示例。

library(jsonlite) 

# Create sample data frame 
> d1 <- data.frame(id=c(1,2),B=c(0,1), C=c(1,0), D=c(0,0)) 


# Add a column concatenating B,C and D 
> d1$x <- with(d1, paste(B, C, D,sep=",")) 
> d1 
    id B C D  x 
1 1 0 1 0 0,1,0 
2 2 1 0 0 1,0,0 
> 

# Add opening and closing square brackets 
> d1$x <- with(d1, paste("[",x,sep = "")) 
> d1 
    id B C D  x 
1 1 0 1 0 [0,1,0 
2 2 1 0 0 [1,0,0 
> d1$x <- with(d1, paste(x,"]",sep = "")) 

> d1 
    id B C D  x 
1 1 0 1 0 [0,1,0] 
2 2 1 0 0 [1,0,0] 
> 

# Subset the columns we need 
> d2 <- d1[,c("id","x")] 
> d2 
    id  x 
1 1 [0,1,0] 
2 2 [1,0,0] 

# create JSON 
> x <- toJSON(d2) 
> x 
[{"id":1,"x":"[0,1,0]"},{"id":2,"x":"[1,0,0]"}]