Homunculus Reticulli Homunculus Reticulli - 6 days ago 6
R Question

Programatically creating a data frame and adding rows to it

I have recently started using R and am still getting used to its data types etc. I am fetching data from a database, performing calculations on the data, and then storing some results back to the database.

The calculated data is to be stored in a specific table in the database. I want to create a data frame with columns matching that of the db table (i.e. same name and data type [near as]). In order to do that, I need to be able to do the following:


  1. Programatically create a data frame with specified 'columns'
    I know I can create this with data.frame() but its not clear how to create a data frame with only column headings, but no data (rows) yet.

  2. Programatically add rows to the empty data frame created in step 1 above



Any help (preferably with a snippet) will be very useful

Answer
empty <- data.frame(a = numeric(), b = factor(), c = character())
filled <- rbind(empty, data.frame(a = 1, b = factor("abc"), c = "def"))

Here it is in action:

> empty <- data.frame(a = numeric(), b = factor(), c = character())
> empty
[1] a b c
<0 rows> (or 0-length row.names)
> empty$a
numeric(0)
> empty$b
factor(0)
Levels: 
> empty$c
character(0)
> filled <- rbind(empty, data.frame(a = 1, b = factor("abc"), c = "def"))
> summary(filled)
       a       b          c            
 Min.   :1   abc:1   Length:1          
 1st Qu.:1           Class :character  
 Median :1           Mode  :character  
 Mean   :1                             
 3rd Qu.:1                             
 Max.   :1   
Comments