Append a data frame to a list

后端 未结 1 1082
独厮守ぢ
独厮守ぢ 2021-02-05 08:28

I\'m trying to figure out how to add a data.frame or data.table to the first position in a list.

Ideally, I want a list structured as follows:

List of 4
         


        
1条回答
  •  一向
    一向 (楼主)
    2021-02-05 08:51

    The issue you are having is that to put a data frame anywhere into a list as a single list element, it must be wrapped with list(). Let's have a look.

    df <- data.frame(1, 2, 3)
    x <- as.list(1:3)
    

    If we just wrap with c(), which is what append() is doing under the hood, we get

    c(df)
    # $X1
    # [1] 1
    #
    # $X2
    # [1] 2
    #
    # $X3
    # [1] 3
    

    But if we wrap it in list() we get the desired list element containing the data frame.

    list(df)
    # [[1]]
    #   X1 X2 X3
    # 1  1  2  3
    

    Therefore, since x is already a list, we will need to use the following construct.

    c(list(df), x) ## or append(x, list(df), 0)
    # [[1]]
    #   X1 X2 X3
    # 1  1  2  3
    #
    # [[2]]
    # [1] 1
    #
    # [[3]]
    # [1] 2
    #
    # [[4]]
    # [1] 3
    

    0 讨论(0)
提交回复
热议问题