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:
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.
Programmatically add rows to the empty data frame created in step 1 above
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With