【问题标题】:How can a dataframe containing a vector list have a different length when unlisted?未列出时,包含矢量列表的数据框如何具有不同的长度?
【发布时间】:2020-05-22 20:21:10
【问题描述】:

给定一个长度为n 的数据框,我运行了一个应用函数并将结果分配给数据框上的一个新列:

my_df$index <- sapply(my_df$local_db_uuid,function(x) which(my_df$remote_db_uuid== x))

但是,我注意到以下内容:

join_ref_id_complete$index %>% length()
# returns length of dataframe rows

对比:

join_ref_id_complete$index %>% unlist() %>% length()
# returns less than length of dataframe rows

这里的长度是怎么回事?这些是缺失值吗?

【问题讨论】:

    标签: r list vector apply


    【解决方案1】:

    有可能某些list 元素没有匹配项并返回integer(0),而unlisting 则将其删除。用一个简单的例子

    lst1 <- list(c(5, 0), c(3, 2, 4), 5)
    sapply(lst1, function(x) which(x == 5))
    #[[1]]
    #[1] 1
    
    #[[2]]
    #integer(0)
    
    #[[3]]
    #[1] 1
    

    当我们unlist时,第二个元素被丢弃

    unlist(sapply(lst1, function(x) which(x == 5)))
    #[1] 1 1
    

    返回 2 而不是 3 的 length

    但是,长度较短只是巧合。它也可以更好

    lst1 <- list(c(5, 0, 5, 5), c(3, 2, 4), c(5, 3, 5))
    unlist(sapply(lst1, function(x) which(x == 5)))
    #[1] 1 3 4 1 3
    

    这里,lengthlistlength 多 5。也可能只是巧合

    【讨论】:

    • 伟大的标注 akrun。此列表中违规值的格式为 $'17027407-f95b-40c4-8802-25945b5a82c2' integer(0)
    猜你喜欢
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 2017-10-31
    • 2020-08-16
    • 2019-12-21
    • 1970-01-01
    • 2021-11-14
    • 2018-09-28
    相关资源
    最近更新 更多