我試圖使用下面的函數嵌套JSON文件轉換成數據幀R:如何讓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文件大約有10萬個觀測值,所以需要永遠返回一個數據幀(我一直等待超過30分鐘,仍然沒有結果)。我認爲可能有一種方法可以同時運行所有temp
行,這應該可以節省大量時間,但我不確定如何在我的代碼中實現這一點。
爲了讓您瞭解我所尋找的輸出,我將我的功能限制在for (i in 1:3)
之下,它產生了以下數據幀。我的問題是如何做同樣的事情,但對於100,000個觀察。請注意,json示例對應於示例輸出。
所需的輸出:
使用JSON解析包,如'jsonlite'或'RJSONIO'或'rjson'。 – alistaire
@alistaire謝謝,但我的json文件嵌套太深,所以軟件包不能完成這項工作。實際上,我使用'jsonlite'來返回一個數據幀,但是是一個半json格式。我正在尋找一個經典的表視圖數據框架。 – Misha
在這種情況下,您需要更清楚地呈現您的問題,並提供示例數據。閱讀:http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – alistaire