【问题标题】:How to change the class of a list from array to list?如何将列表的类从数组更改为列表?
【发布时间】:2016-11-14 17:43:16
【问题描述】:

我有一个数据框,其中包含必须转换为向量列表的名称和值。这些名称决定了每个值必须分配到哪个向量中。为了自动创建我的列表,我使用了 tapply:

d_df <- data.frame(name=c(rep("a",5),rep("b",5)),value=LETTERS[1:10])
d_list_auto <- tapply(d_df$value,d_df$name, FUN=as.character)
d_list_auto <- unname(d_list_auto)
d_list_manual <- list(LETTERS[1:5],LETTERS[6:10])

为了实际效果,d_list_auto 和 d_list_manual 是同一个东西,但是它们的类不同(而且我传递列表的函数抱怨它)。

class(d_list_auto) #array
class(d_list_manual) #list

我试图用 as.list() 和不同风格的 apply 函数强制更改类,但无济于事:

class(as.list(d_list_auto)) #array
apply(d_list_auto,1,as.list) #Creates a list of lists

如何在不丢失数据结构的情况下强制 d_list_auto 进入类列表?

编辑

一个非常讨厌的解决方案:

class(apply(d_list_auto,1,as.list)) #list

有人有更优雅的建议吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    首先让我们看一下每个对象的结构:

    str(d_list_auto)
    # List of 2
    #  $ : chr [1:5] "A" "B" "C" "D" ...
    #  $ : chr [1:5] "F" "G" "H" "I" ...
    #  - attr(*, "dim")= int 2
    
    str(d_list_manual)
    # List of 2
    #  $ : chr [1:5] "A" "B" "C" "D" ...
    #  $ : chr [1:5] "F" "G" "H" "I" ...
    

    看起来唯一的区别是d_list_auto 有一个dim 属性,从tapply() 遗留下来。我们可以通过将NULL 指定为新维度来删除它。

    dim(d_list_auto) <- NULL
    

    现在让我们看看它是否有效:

    class(d_list_auto)
    # [1] "list"
    identical(d_list_auto, d_list_manual)
    # [1] TRUE
    

    【讨论】:

    • 手动执行lapply(split(),...) 可能是另一种选择,但我认为需要unnamed 才能完全匹配输出。
    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 2022-01-11
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多