42

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

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

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

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.

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Tom
  • 1,221
  • 1
  • 12
  • 13
  • Richard, This is not what I am trying to do. I am trying to add an object to a list that is already defined. Yes, I could redefine the whole list, but I was hoping not to need to do that. What I would like to do is to insert an object into a list with as little trouble as possible. The list is rather long and I would rather not restructure the whole list that way. I do see your point on the use of append as being designed for vectors, but it seems like there should be a corresponding function for lists, no? – Tom Oct 16 '15 at 18:28
  • That does it! Could you move your comment to an answer so I can mark it as selected? – Tom Oct 16 '15 at 18:34
  • A better title might be "prepend to list" or something. This doesn't seem related to data.table in particular, nor really appending. – Frank Oct 16 '15 at 18:36

1 Answers1

59

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
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
  • This worked very well. Thanks. FWIW it also seems to play nice with data.table too. – Tom Oct 17 '15 at 22:45