【问题标题】:How to convert a nested lists to dataframe in R?如何将嵌套列表转换为 R 中的数据框?
【发布时间】:2017-12-08 18:39:47
【问题描述】:

我有一个要转换为数据框的嵌套列表。

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 进行转换时遇到了同样的问题:df &lt;- data.frame(do.call(rbind, All)),但我不知道出了什么问题。

【问题讨论】:

  • df$iter1 无法返回 data.frame! data.frame 的一项可以是向量或列表。顺便说一句 df 是一个数据框,但它的项目是列表而不是向量。假设您希望它们分别是数字和字符值的向量?

标签: r


【解决方案1】:
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

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

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

【讨论】:

  • 对于最后一个:这是完美的方式@d.b!并且 as.data.frame(data.table::rbindlist(All, idcol = TRUE)) 必要时将其转换为数据框。
【解决方案2】:

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

【讨论】:

  • 它们是因素。如果您提供 stringsAsFactors = F,它们都会被强制转换为字符。我认为第一列应该是数字(1,1)和第二个字符(a,b)?
  • 你可以转置并使列数字化吗?
  • 我想要的是一个数据框,以便df$item1 返回一个包含item1 列的数据框。
  • 这是一种方式,但不是 R 方式。如果你有 100 列呢?
  • @SerhatCevikel:当然,不是很通用
【解决方案3】:

我认为您希望第一列是数字向量,如 1,1,第二列是字符向量,如“a”和“b”?

这个怎么样:

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

【讨论】:

  • 你有 iter1, iter2 作为 col 和 row 的名称,但我猜它们只属于行,而 cols 应该有 item1, item2。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
  • 2018-02-14
  • 1970-01-01
相关资源
最近更新 更多