【问题标题】:Convert list to dataframe in R when dataframes in list are named NULL当列表中的数据框命名为 NULL 时,将列表转换为 R 中的数据框
【发布时间】:2013-09-05 19:16:23
【问题描述】:

在使用RCurl 进行网络抓取后,我使用了XMLreadHTMLTable,现在有一个包含 100 个数据框的列表,其中包含对两个变量的 40 个观察值。我想将其转换为 100 行和 40 列的单个数据框。每个数据框中的第一列包含我希望在单个数据框中成为列名的内容。这与 MWE 最接近(我的实际列表中的每个数据帧都命名为 NULL):

description <- c("name", "location", "age")
value <- c("mike", "florida", "25")
df1 <- data.frame(description, value)
description <- c("name", "location", "tenure")
value <- c("jim", "new york", "5")
df2 <- data.frame(description, value)
list <- list(df1, df2)

# list output
[[1]]
  description   value
1        name    mike
2    location florida
3         age      25

[[2]]
  description    value
1        name      jim
2    location new york
3      tenure        5

这是我希望实现的一般输出:

library(reshape2)
listm <- melt(list)
dcast(listm, L1 ~ description)
# dcast output
  L1  age location name tenure
1  1   25  florida mike   <NA>
2  2 <NA> new york  jim      5

如上所述,我不知道如何通过 MWE 表示的问题是,每个数据帧都被命名为 NULL,因此没有唯一标识符可用于 cast 数据.

我该如何处理reshape2 和/或plyr 中的这个问题?

【问题讨论】:

    标签: r plyr reshape2


    【解决方案1】:

    您可以在列表中每个 data.frame 的行上使用 rep 来获取 L1 列。然后就可以直接投射了:

    # ll is your list of data.frames
    ll.df <- cbind(L1 = rep(seq_along(ll), sapply(ll, nrow)), do.call(rbind, ll))
    
    require(reshape2)
    dcast(ll.df, L1 ~ description)
      L1  age location name tenure
    1  1   25  florida mike   <NA>
    2  2 <NA> new york  jim      5
    

    【讨论】:

    • 我收到以下错误:Error in rbind(deparse.level, ...) : numbers of columns of arguments do not match。有什么想法吗?谢谢。
    • sapply(ll, ncol) 帮助我识别了一个包含 3 列的格式错误的数据框。我删除了它,您的解决方案有效。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 2015-04-16
    相关资源
    最近更新 更多