如何将嵌套列表转换为R中的数据帧?

时间:2017-12-08 18:39:48

标签: r

我有一个嵌套列表,我想将其转换为数据帧。

git bisect

但我的问题是iter1 <- list(item1 = 1, item2 = "a") iter2 <- list(item1 = 1, item2 = "b") All <- list(iter1 = iter1, iter2 = iter2) df <- data.frame(t(sapply(All,c))) # Convert list to dataframe 返回一个列表而不是数据帧,任何想法?

df$iter1

使用> class(df) [1] "data.frame" > df$item1 $iter1 [1] 1 $iter2 [1] 1 进行转换时遇到同样的问题:do.call但我无法弄清楚出了什么问题。

3 个答案:

答案 0 :(得分:3)

temp = unique(unlist(lapply(All, names)))
mydf = setNames(object = data.frame(lapply(temp, function(nm)
    unlist(lapply(All, function(x) x[[nm]])))), nm = temp)

mydf
#      item1 item2
#iter1     1     a
#iter2     1     b

OR

do.call(rbind, lapply(All, data.frame))
#      item1 item2
#iter1     1     a
#iter2     1     b

OR

data.table::rbindlist(All, idcol = TRUE)
#     .id item1 item2
#1: iter1     1     a
#2: iter2     1     b

答案 1 :(得分:0)

lapply会做你想做的事吗?:

iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

然后:

df <- as.data.frame(lapply(All, unlist))

> str(df)
'data.frame':   2 obs. of  2 variables:
 $ iter1: Factor w/ 2 levels "1","a": 1 2
 $ iter2: Factor w/ 2 levels "1","b": 1 2

答案 2 :(得分:0)

我认为您希望第一列为数字向量为1,1而第二列为字符向量为&#34; a&#34;和&#34; b&#34;?

这个怎么样:

iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

extract <- function(x, listx) sapply(listx, "[[", x)

df <- lapply(1:2, extract, All)
df <- as.data.frame(df, col.names = names(All), stringsAsFactors = F)
df

如果你想要一个单行:

df <- as.data.frame(lapply(1:2, function(x, listx) sapply(listx, "[[", x), All), col.names = names(All), stringsAsFactors = F)
df