2016-10-24 106 views
2

我有我想要的最後一列轉換爲對應的[R存儲,這將類似於包含JSON數據作爲在下面的示例中的列,轉換R數據表列

library(data.table) 
test <- data.table(a = list(1,2,3), 
      info = list("{'duration': '10', 'country': 'US'}", 
         "{'duration': '20', 'country': 'US'}", 
         "{'duration': '30', 'country': 'GB', 'width': '20'}")) 

到,

res <- data.table(a = list(1, 2, 3), 
        duration = list(10, 20, 30), 
        country = list('US', 'US', 'GB'), 
        width = list(NA, NA, 20)) 

由於我有500K行不同的內容,我會尋找一個快速的方法來做到這一點。

+1

好吧,隨時編輯,如果你知道如何以某種方式糾正它,不會打破答案。 – Frank

回答

3

的變化,而不需要分離出JSON字符串

library(data.table) 
library(jsonlite) 

test[, info := gsub("'", "\"", info)] 
test[, rbindlist(lapply(info, fromJSON), use.names = TRUE, fill = TRUE)] 

# duration country width 
# 1:  10  US NA 
# 2:  20  US NA 
# 3:  30  GB 20 
+0

好的數據表解決方案!正是我在找什麼。 – Stereo

3

第一解析JSON,然後構建data.frame(或data.table):

json_string <- paste(c("[{'duration': '10', 'country': 'US'}", 
    "{'duration': '20', 'country': 'US'}", 
    "{'duration': '30', 'country': 'GB'}", 
    "{'width': '20'}]"), collapse=", ") 

# JSON standard requires double quotes 
json_string <- gsub("'", "\"", json_string) 

library("jsonlite") 
fromJSON(json_string) 

# duration country width 
# 1  10  US <NA> 
# 2  20  US <NA> 
# 3  30  GB <NA> 
# 4  <NA> <NA> 20 

這不正是你問什麼作爲你的JSON不關聯的「寬度」與此前的紀錄,您可能需要首先做一些操作:

json_string <- paste(c("[{'duration': '10', 'country': 'US'}", 
    "{'duration': '20', 'country': 'US'}", 
    "{'duration': '30', 'country': 'GB', 'width': '20'}]"), 
    collapse=", ") 

json_string <- gsub("'", "\"", json_string) 
df <- jsonlite::fromJSON(json_string) 
data.table::as.data.table(df) 

# duration country width 
# 1:  10  US NA 
# 2:  20  US NA 
# 3:  30  GB 20 
+1

考慮使用'setDT(df)'代替'data.table :: as.data.table(df)' – SymbolixAU