Essi Shams Essi Shams - 1 year ago 80
R Question

Adding a vector as a new column to a dataframe

MyDataframe is a dataframe which has 7 columns now of the character, numeric and date data types. The dataframe has 300,000 rows.

I need to have a vector as a new field for each row of the data table. I need the vector to have 1440 zeros initially. Let's call this MyVector.

If I try this:

MyDataframe$MyVector = numeric(1440)

I get an error message saying that the number of rows in the dataframe dont match the length of the vector. This tells me that R is trying to add the whole vector as a column in the dataframe.

How do I add the vector, so that each row of the dataframe will have a vector as a member?

Answer Source

The stackoverflow data.frame documentation is very helpful. As you see, a data.frame is a special type of list. It can have any kind of object in it: others lists (such as models), data.frames or even vectors. In those cases, the data.frame is known as nested data.frame, that's the term you need to search for.

You can produce it like this:

df <- data.frame(a = 1:3, b = letters[1:3])
df$vectors <- list(numeric(3), numeric(3), numeric(3))
'data.frame':   3 obs. of  3 variables:
 $ a      : int  1 2 3
 $ b      : Factor w/ 3 levels "a","b","c": 1 2 3
 $ vectors:List of 3
  ..$ : num  0 0 0
  ..$ : num  0 0 0
  ..$ : num  0 0 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download