将给定列表转换为数据帧

jan*_*an5 0 r

我有以下列表:

$id1
$id1[[1]]
         A              B               
        "A"            "B"                
$id1[[2]]
         A             B 
        "A"           "A1" 
$id2
$id2[[1]]
         A              B               
        "A2"           "B2" 
Run Code Online (Sandbox Code Playgroud)

在R-pastable形式:

dat = structure(list(SampleTable = structure(list(id2 = list(structure(c("90", "7"), .Names = c("T", "G")), structure(c("90", "8"), .Names = c("T", "G"))), id1 = structure(c("1", "1"), .Names = c("T", "G"))), .Names = c("id2", "id1"))), .Names = "SampleTable") 
Run Code Online (Sandbox Code Playgroud)

我希望将此给定列表转换为以下数据帧:

id1   A    B
id1   A    A1 
id2   A2   B2 
Run Code Online (Sandbox Code Playgroud)

Vin*_*ynd 5

您的数据结构(显然是未命名的1行data.frames列表的命名列表)有点复杂:最简单的可能是使用循环来构建data.frame.

它可以直接与完成do.call,lapply以及rbind,但它不是非常具有可读性,即使你所熟悉的那些功能.

# Sample data 
d <- list(
  id1 = list(
    data.frame( x=1, y=1 ),
    data.frame( x=2, y=2 )
  ),
  id2 = list(
    data.frame( x=3, y=3 ),
    data.frame( x=4, y=4 )
  ),
  id3 = list(
    data.frame( x=5, y=5 ),
    data.frame( x=6, y=6 )
  )
)

# Convert
d <- data.frame(
  id=rep(names(d), unlist(lapply(d,length))),
  do.call( rbind, lapply(d, function(u) do.call(rbind, u)) )
)
Run Code Online (Sandbox Code Playgroud)

其他解决方案,使用循环,如果你有一个参差不齐的数据结构,包含矢量(而不是data.frames),如评论中所述.

d <- structure(list(SampleTable = structure(list(id2 = list(structure(c("90", "7"), .Names = c("T", "G")), structure(c("90", "8"), .Names = c("T", "G"))), id1 = structure(c("1", "1"), .Names = c("T", "G"))), .Names = c("id2", "id1"))), .Names = "SampleTable") 
result <- list()
for(i in seq_along(d$SampleTable)) {
  id <- names(d$SampleTable)[i]
  block <- d$SampleTable[[i]]
  if(is.atomic(block)) {
    block <- list(block)
  }
  for(row in block) {
    result <- c(result, list(data.frame(id, as.data.frame(t(row)))))
  }    
}
result <- do.call(rbind, result)
Run Code Online (Sandbox Code Playgroud)