将数据框附加到列表 [英] Append a data frame to a list

查看:51
本文介绍了将数据框附加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何将data.frame或data.table添加到列表的第一位置。

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
 $  :'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

请注意data.frame是一个列表结构中的对象。

Note the data.frame is an object within the structure of the list.

问题是创建列表后,我需要将数据框添加到列表中,并且数据框必须是列表中的第一个元素。我想使用类似 append 这样的简单方法来做到这一点,但是当我尝试时:

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(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

当我尝试追加时,R似乎将data.frame强制转换为列表。我如何防止它这样做?或者,可以使用什么替代方法来构造此列表,即在列表最初创建之后将data.frame插入列表中位置1的列表中。

It appears that R is coercing data.frame into a list when I'm trying to append. 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.

推荐答案

您遇到的问题是,要将数据框的任何位置作为单个列表元素放入列表中,必须使用 list()进行包装。让我们看一下。

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)

如果我们只用 c( ),这就是 append()在后台执行的操作,我们得到

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

但是如果将其包装在 list()中,则会得到包含数据框的所需列表元素。

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

因此,由于 x 已经是一个列表,因此我们需要使用以下构造。 / p>

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

这篇关于将数据框附加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆