簡體   English   中英

在R中將遞歸列表轉換為動態data.frame

[英]Convert recursive lists to dynamic data.frame in R

我需要構建一個以遞歸方式遍歷列表和子列表,然后轉換為data.frame的函數。 假設我有一個這樣的清單

from <- list(id="12345678", name="Gabriele")
message <- "The quick fox"
comments <- list(list(name="Mickey", comment="Hello world!"), list(name="Donald", message="World...hello!"))

big.list <- list(from, message, comments)

我需要使用此架構將其轉換為data.frame的形式

from_id, from_name, message, comments_name, comments_message

(換句話說,將子列表展平)

問題是我事先不知道列表中有哪些字段,而我沒有(例如,某些帖子可能會完全忽略注釋部分)。

以下是快速試用。 如果big.list有名稱,則可以將它們用作列名稱。

內部的do.call()使子列表變平,而外部的do.call()轉換為數據幀。

lst1 <- list(from = list(id="12345678", name="Gabriele"),message = "The quick fox",
             comments = list(list(name="Mickey", comment="Hello world!"),
                            list(name="Donald", message="World...hello!")))
lst2 <- list(from = list(id="12345678", name="Gabriele"),message = "The quick fox",
             comments = list(list(name="Mickey", comment="Hello world!")))
lst3 <- list(from = list(id="12345678", name="Gabriele"),message = "The quick fox")

df1 <- do.call(data.frame, do.call(c, lst1))
df2 <- do.call(data.frame, do.call(c, lst2))
df3 <- do.call(data.frame, do.call(c, lst3))

df1
#from.id from.name       message comments1.name comments1.comment comments2.name comments2.message
#1 12345678  Gabriele The quick fox         Mickey      Hello world!         Donald    World...hello!

df2
#from.id from.name       message comments.name comments.comment
#1 12345678  Gabriele The quick fox        Mickey     Hello world!

df3
#from.id from.name       message
#1 12345678  Gabriele The quick fox

@加布里埃爾B

以下是笨拙但可行的解決方案。 其他人可能會發布更好的。

from <- list(id="12345678", name="Gabriele")
message <- "The quick fox"
comments <- list(list(name="Mickey", comment="Hello world!"), list(name="Donald", message="World...hello!"))
big.list <- list(from = from, message = message, comments = comments)
big.list1 <- list(from = from, message = message)

join <- function(lst) {
  if(length(lst$comments) < 1) {
    bnd <- data.frame(id = unlist(lst$from)[1], name = unlist(lst$from)[2], lst$message)
    bnd$cmt.name <- "na"
    bnd$comment <- "na"
    bnd
  } else {
    bnd <- do.call(rbind, lapply(1:length(lst$comments), function(x) {
      id <- unlist(lst$from)[1]
      name <- unlist(lst$from)[2]
      data.frame(id = id, name = name, lst$message)
    }))
    bnd <- cbind(bnd, do.call(rbind, lst$comments))
    names(bnd) <- c("id", "name", "message", "cmt.name", "comment")
    bnd
  }  
}

join(big.list)
#id     name       message cmt.name        comment
#id  12345678 Gabriele The quick fox   Mickey   Hello world!
#id1 12345678 Gabriele The quick fox   Donald World...hello!

join(big.list1)
#id     name   lst.message cmt.name comment
#id 12345678 Gabriele The quick fox       na      na

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM