Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically creating a data frame and adding rows to it

Tags:

r

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. Programmatically 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. Programmatically add rows to the empty data frame created in step 1 above

like image 994
Homunculus Reticulli Avatar asked Jan 20 '12 10:01

Homunculus Reticulli


1 Answers

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   
like image 132
Thierry Avatar answered Oct 28 '22 09:10

Thierry