我尝试使用以下函数将嵌套的json文件转换为R中的数据框:
rf1 <- function(data) {
master <-
data.frame(
id = character(0),
awardAmount = character(0),
awardStatus = character(0),
tenderAmount = character(0)
)
for (i in 1:nrow(data)) {
temp1 <- unlist(data$data$awards[[i]]$status)
length <- length(temp1)
temp2 <- rep(data$data$id[i], length)
temp3 <- rep(data$data$value$amount[[i]], length)
temp4 <- unlist(data$data$awards[[i]]$value[[1]])
tempDF <-
data.frame(id = temp2,
awardAmount = temp4,
awardStatus = temp1,
tenderAmount = temp3)
master <- rbind(master, tempDF)
}
return(master)
}
以下是我使用的json文件的示例:
{
"data" : {
"id" : "3f066cdd81cf4944b42230ed56a35bce",
"awards" : [
{
"status" : "unsuccessful",
"value" : {
"amount" : 76
}
},
{
"status" : "active",
"value" : {
"amount" : 41220
}
}
],
"value" : {
"amount" : 48000
}
}
},
{
"data" : {
"id" : "9507162e6ee24cef8e0ea75d46a81a30",
"awards" : [
{
"status" : "active",
"value" : {
"amount" : 2650
}
}
],
"value" : {
"amount" : 2650
}
}
},
{
"data" : {
"id" : "a516ac43240c4ec689f3392cf0c17575",
"awards" : [
{
"status" : "active",
"value" : {
"amount" : 2620
}
}
],
"value" : {
"amount" : 2650
}
}
}
正如你所看到的,这三个观察的奖项数量不同(第一个观察有两个奖项,而另外两个只有一个奖励)。由于我正在查找表格视图数据框,因此我使用data$id
和data$value$amount
等重复信息填充空单元格。
json文件大约有100,000个观察值,因此返回一个数据帧需要永远(我已经等待了30多分钟,但仍然没有结果)。我认为可能有一种方法可以并行运行所有temp
行,这可以节省大量时间,但我不知道如何在我的代码中实现它。
为了让您了解我正在寻找的输出,我将我的功能限制在for (i in 1:3)
,这产生了以下数据帧。我的问题是如何做同样的事情,但是对于100,000次观察。注意,json示例对应于示例输出。
期望的输出:
答案 0 :(得分:1)
这绝不是优雅的,但似乎有效:
library(jsonlite)
library(purrr)
library(dplyr)
json_data <- '[{"data":{"id":"3f066cdd81cf4944b42230ed56a35bce","awards":[{"status":"unsuccessful","value":{"amount":76}},{"status":"active","value":{"amount":41220}}],"value":{"amount":48000}}},{"data":{"id":"9507162e6ee24cef8e0ea75d46a81a30","awards":[{"status":"active","value":{"amount":2650}}],"value":{"amount":2650}}},{"data":{"id":"a516ac43240c4ec689f3392cf0c17575","awards":[{"status":"active","value":{"amount":2620}}],"value":{"amount":2650}}}] '
# parse original JSON records
parsed_json_data <- fromJSON(json_data)$data
# extract awards data, un-nest the nested parts, and re-assemble awards into a data frame for each id
awards <- map2(.x = parsed_json_data$id,
.y = parsed_json_data$awards,
.f = function(x, y) bind_cols(data.frame('id' = rep(x, nrow(y)), stringsAsFactors = FALSE), as.data.frame(as.list(y))))
# bind together the data frames over all ids
awards <-
bind_rows(awards) %>%
rename(awards_status = status, awards_amount = amount)
# remove awards data from original parsed data
parsed_json_data$awards <- NULL
# un-nest the remaining data structures
parsed_json_data <- as.data.frame(as.list(parsed_json_data), stringsAsFactors = FALSE)
# join higher-level data with awards data (in denormalisation process)
final_data_frame <- inner_join(parsed_json_data, awards, by = 'id')
final_data_frame
# id amount awards_status awards_amount
# 1 3f066cdd81cf4944b42230ed56a35bce 48000 unsuccessful 76
# 2 3f066cdd81cf4944b42230ed56a35bce 48000 active 41220
# 3 9507162e6ee24cef8e0ea75d46a81a30 2650 active 2650
# 4 a516ac43240c4ec689f3392cf0c17575 2650 active 2620
答案 1 :(得分:1)
另一种方法是删除工作表单R并重新构建你的mongodb查询。
如果这是您在mongodb中的数据
在mongo shell中,您可以按照
的方式编写查询db.json.aggregate([
{ "$unwind" : "$data.awards"},
{ "$group" : {
"_id" : {"id" : "$data.id", "status" : "$data.awards.status"},
"awardAmount" : { "$sum" : "$data.awards.value.amount" },
"tenderAmount" : { "$sum" : "$data.value.amount" }
}
},
{ "$project" : {
"id" : "$_id.id",
"status" : "$_id.status",
"awardAmount" : "$awardAmount",
"tenderAmount" : "$tenderAmount",
"_id" : 0} }
])
(注意:我不是mongodb专家,因此可能会有一种更为简洁的写作方式)
您也可以在R
中使用library(mongolite)
mongo <- mongo(collection = "json", db = "test")
qry <- '[
{ "$unwind" : "$data.awards"},
{ "$group" : {
"_id" : {"id" : "$data.id", "status" : "$data.awards.status"},
"awardAmount" : { "$sum" : "$data.awards.value.amount" },
"tenderAmount" : { "$sum" : "$data.value.amount" }
}
},
{ "$project" : {
"id" : "$_id.id",
"status" : "$_id.status",
"awardAmount" : "$awardAmount",
"tenderAmount" : "$tenderAmount",
"_id" : 0}
}
]'
df <- mongo$aggregate(pipeline = qry)
df
# awardAmount tenderAmount id status
# 1 2620 2650 a516ac43240c4ec689f3392cf0c17575 active
# 2 41220 48000 3f066cdd81cf4944b42230ed56a35bce active
# 3 2650 2650 9507162e6ee24cef8e0ea75d46a81a30 active
# 4 76 48000 3f066cdd81cf4944b42230ed56a35bce unsuccessful
答案 2 :(得分:1)
这可能是最简单的方法。它不使用JSON解析,而是使用一堆正则表达式
但是,我同意SymbolixAU在mongo查询中这样做是可行的。
# load json file ("file.json") just as a single string / single-element character vector
jsonAsString <- readChar("file.json", file.info("file.json")$size)
# chunk the tenders
dataChunks <- unlist(strsplit(jsonAsString, '"data" : \\{'))
dataChunks <- dataChunks[grepl("id", dataChunks)] # this removes the unnecessary header
# get the award subchunks
awardSubChunks <- gsub('.*("awards".*?}.*?}.*?]).*', "\\1", dataChunks)
# scrape status values out of the award subchunks
statusIndex <- gregexpr('(?<="status" : ")([[:alnum:]]*)', awardSubChunks, perl = T)
status <- unlist(regmatches(awardSubChunks, statusIndex))
# scrape bidAmount value out of the award subchunks
bidAmountIndex <- gregexpr('(?<="amount" : )([[:alnum:]]*)', awardSubChunks, perl = T)
bidAmount <- unlist(regmatches(awardSubChunks, bidAmountIndex))
# get the id and tender by removing the award subchunks
idTenderAmount <- gsub('"awards".*?}.*?}.*?]', "", dataChunks)
# scrape id and tenderAmount values
id <- gsub('.*"id" : "([[:alnum:]]*)".*', "\\1", idTenderAmount)
tenderAmount <- gsub('.*"amount" : ([[:alnum:]]*).*', "\\1", idTenderAmount)
# find the number of bids per Id in order to find number of times id and tenderAmount needs to be repeated
numBidsPerId <- gregexpr("value", awardSubChunks)
numBidsTotal <- sapply(numBidsPerId, length)
# putting things together
df <- data.frame(id = rep(id, numBidsTotal),
tenderAmount = rep(tenderAmount, numBidsTotal),
status = status,
bidAmount = bidAmount)