18

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

1 Answer 1

28
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   
Sign up to request clarification or add additional context in comments.

2 Comments

BTW, is it ok for me to replace filled <- rbind(empty, data.frame(a = 1, b = factor("abc"), c = "def")) with: empty <- rbind(empty, data.frame(a = 1, b = factor("abc"), c = "def")) So that I am not creating a new data frame for each row added?
You can do that. But anyway: you are in the second circle of the R inferno: burns-stat.com/pages/Tutor/R_inferno.pdf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.