【问题标题】:Make vector of each column of a dataframe and return the vectors in a list制作数据框每一列的向量并返回列表中的向量
【发布时间】:2021-01-20 10:15:39
【问题描述】:

我有一个像这样的数据框:

df<-data.frame(x=1:5,y=6:10,z=11:15)



 x  y  z
1 1  6 11
2 2  7 12
3 3  8 13
4 4  9 14
5 5 10 15

现在我想创建一个列表new_list,其中每个元素都是一个向量列。

这看起来像:

str(new_list)
list of 3
$ : num[1:5] 1 2 3 4 5
$ : num[1:5] 6 7 8 9 10
$ : num[1:5] 11 12 13 14 15

我试过了:

new_list <-lapply(df,c)

但这只是返回

list of 3
$ : num[1:5] 1
$ : num[1:5] 6
$ : num[1:5] 11

注意:我希望我的目标很明确。如果不是请告诉我。

【问题讨论】:

  • 数据框已经是列的列表...如果您告诉我们为什么要这样做,我们可能会提供更多帮助。

标签: r list dataframe vector


【解决方案1】:

使用identity()

lapply(df, identity)

只是修改属性和类:

new_list <- unclass(df)
attr(new_list, "row.names") <- NULL

或者

new_list <- df
class(new_list) <- "list" # NULL also works but is not as clear
attr(new_list, "row.names") <- NULL

【讨论】:

    【解决方案2】:

    data.frame 只是一个带有一些附加属性的列表。将data.frame 转换为具有您请求的结构的列表的最简单方法是删除所有属性。

    如果你需要创建一个新的对象,你可以复制现有的,然后剥离它。

    new_list <- df
    
    attributes(new_list) <- NULL
    
    > str(new_list)
    List of 3
     $ : int [1:5] 1 2 3 4 5
     $ : int [1:5] 6 7 8 9 10
     $ : int [1:5] 11 12 13 14 15
    

    然而,这通常是使用as.list()“在野外”完成的,尽管这会保留变量名并且有一些额外的开销。

    【讨论】:

      【解决方案3】:

      使用c

      l <- lapply(df, c)
      str(l)
      # List of 3
      #  $ x: int [1:5] 1 2 3 4 5
      #  $ y: int [1:5] 6 7 8 9 10
      #  $ z: int [1:5] 11 12 13 14 15
      

      as.list

      l <- as.list(df)
      str(l)
      # List of 3
      #  $ x: int [1:5] 1 2 3 4 5
      #  $ y: int [1:5] 6 7 8 9 10
      #  $ z: int [1:5] 11 12 13 14 15
      

      【讨论】:

      • unname(as.list(df))
      • @Roland 为什么要打扰unname()
      • 在您提供的示例中,列表元素未命名。
      • @GregorThomas 为什么要删除 class 属性(正如您在问题下评论的那样)?我只是想补充一小步以得出 OP 的预期结果。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 1970-01-01
      • 2018-07-12
      相关资源
      最近更新 更多