2017-04-08 77 views
1
 email foo bar 
1 [email protected] 23  34 
2 [email protected] 43  34 
3 [email protected] 35  32 

現在我想創建用於每個電子郵件JSON文檔作爲以下形式:
DOC 1:{ "email" : "[email protected]"}
文檔2:{ "email" : "[email protected]"}
DOC 3 :{ "email" : "[email protected]"}如何JSON格式的數據幀的列轉換中的R

我的最終目標是使用dbInsertDocument()RMongo將這些文檔插入到MongoDB中。
我一直在玩toJSON(),但無法找出一個辦法。如何在上述JSON文檔中轉換final$email

+0

你可以請檢查下面的答案,並接受其中之一,如果你對theem感到滿意或至少澄清你的問題? – agstudy

回答

0

我不知道這是否是你所需要的: final$email還沒有列名,因此不會在toJSON(final$email)

library(jsonlite) 

txt <- "email foo bar 
1 [email protected] 23 34 
2 [email protected] 43 34 
3 [email protected] 35 32" 

final <- read.table(text=txt, stringsAsFactors = FALSE) 
toJSON(final$email) 
# [1] "[\"[email protected]\",\"[email protected]\",\"[email protected]\"]"  

# final$email has to be converted to data.frame 
dt <- data.frame(final$email) 
colnames(dt) <- "email" 
toJSON(dt) 
# [{"email":"[email protected]"},{"email":"[email protected]"},{"email":"[email protected]"}] 
0

輸出我想包括在內,你應該先轉換您的data.frame列表清單:

## basically you split your data.frame by row 
## for each row you convert it as a list 
LMAo <- unname(lapply(split(dx,seq_len(nrow(dx))), function(x) as.list(x))) 

## auto unboxing to no treat scalar as vector 
jsonlite::toJSON(LMAo,auto_unbox = T) 
[ 
    {"email":"[email protected]","foo":23,"bar":34}, 
    {"email":"[email protected]","foo":43,"bar":34}, 
    {"email":"[email protected]","foo":35,"bar":32} 
] 

## same result using RJSONIO 
cat(RJSONIO::toJSON(LMAo))