【问题标题】:extracting element from list of lists and empty dataframes从列表和空数据框列表中提取元素
【发布时间】:2017-07-12 14:31:17
【问题描述】:

我有一个丑陋的列表和空数据框(API 很有趣!)。我想要的是name 元素的向量。在这种情况下,向量的长度应为 13,NA 为 data frame with 0 columns and 0 rows

myList <- list(structure(list(uuid = "x1", 
    name = "thanks"), .Names = c("uuid", "name"), class = "data.frame", row.names = 1L), 
    structure(list(uuid = "x2", 
        name = "team"), .Names = c("uuid", "name"), class = "data.frame", row.names = 1L), 
    structure(list(), .Names = character(0), row.names = integer(0), class = "data.frame"), 
    structure(list(uuid = "x3", 
        name = "team"), .Names = c("uuid", "name"), class = "data.frame", row.names = 1L), 
    structure(list(uuid = "x4", 
        name = "team"), .Names = c("uuid", "name"), class = "data.frame", row.names = 1L), 
    structure(list(uuid = "x5", 
        name = "enrolled"), .Names = c("uuid", "name"), class = "data.frame", row.names = 1L), 
    structure(list(uuid = "x6", 
        name = "team"), .Names = c("uuid", "name"), class = "data.frame", row.names = 1L), 
    structure(list(), .Names = character(0), row.names = integer(0), class = "data.frame"), 
    structure(list(uuid = "x7", 
        name = "team"), .Names = c("uuid", "name"), class = "data.frame", row.names = 1L), 
    structure(list(), .Names = character(0), row.names = integer(0), class = "data.frame"), 
    structure(list(uuid = "x8", 
        name = "team"), .Names = c("uuid", "name"), class = "data.frame", row.names = 1L), 
    structure(list(uuid = "x9", 
        name = "team"), .Names = c("uuid", "name"), class = "data.frame", row.names = 1L), 
    structure(list(uuid = "x10", 
        name = "team"), .Names = c("uuid", "name"), class = "data.frame", row.names = 1L))

期望的输出:

"thanks" "team" NA "team" "team" "enrolled" "team" NA "team" NA "team" "team" "team"

【问题讨论】:

  • unlist(lapply(myList, function(a) c(a$name, NA)[1 + is.null(a$name)]))

标签: r


【解决方案1】:

也许它对你有用:

sapply(myList, function(x){
    if(all(dim(x) == c(0,0))){
        x <- NA
    } else x <- x$name
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2021-08-23
    • 2015-03-24
    • 1970-01-01
    相关资源
    最近更新 更多