简体   繁体   English

将数据框附加到列表

[英]Append a data frame to a list

I'm trying to figure out how to add a data.frame or data.table to the first position in a list. 我试图弄清楚如何将data.frame或data.table添加到列表中的第一个位置。

Ideally, I want a list structured as follows: 理想情况下,我想要一个结构如下的列表:

List of 4
 $  :'data.frame':  1 obs. of  3 variables:
  ..$ a: num 2
  ..$ b: num 1
  ..$ c: num 3
 $ d: num 4
 $ e: num 5
 $ f: num 6

Note the data.frame is an object within the structure of the list. 请注意,data.frame是列表结构中的一个对象。

The problem is that I need to add the data frame to the list after the list has been created, and the data frame has to be the first element in the list. 问题是我需要在创建列表后将数据框添加到列表中,并且数据框必须是列表中的第一个元素。 I'd like to do this using something simple like append , but when I try: 我想使用像append这样简单的东西来做这件事,但当我尝试时:

append(list(1,2,3),data.frame(a=2,b=1,c=3),after=0)

I get a list structured: 我得到一个结构列表:

str(append(list(1,2,3),data.frame(a=2,b=1,c=3),after=0))
List of 6
 $ a: num 2
 $ b: num 1
 $ c: num 3
 $  : num 1
 $  : num 2
 $  : num 3

It appears that R is coercing data.frame into a list when I'm trying to append . 当我试图append时,似乎R正在将data.frame强制转换为列表。 How do I prevent it from doing so? 我该如何阻止它这样做? Or what alternative method might there be for constructing this list, inserting the data.frame into the list in position 1, after the list's initial creation. 或者可以使用什么替代方法来构造此列表,在列表的初始创建之后将data.frame插入位置1的列表中。

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() . 您遇到的问题是将数据框放在列表中的任何位置作为单个列表元素,它必须用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()包装,这是append()在引擎盖下做的,我们得到

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()我们将得到包含数据框的所需列表元素。

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. 因此,由于x已经是一个列表,我们需要使用以下构造。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM