2016-07-14 78 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]"}]