Skip to content
Fix Code Error

Create an empty data.frame

March 13, 2021 by Code Error
Posted By: Anonymous

I’m trying to initialize a data.frame without any rows. Basically, I want to specify the data types for each column and name them, but not have any rows created as a result.

The best I’ve been able to do so far is something like:

df <- data.frame(Date=as.Date("01/01/2000", format="%m/%d/%Y"), 
                 File="", User="", stringsAsFactors=FALSE)
df <- df[-1,]

Which creates a data.frame with a single row containing all of the data types and column names I wanted, but also creates a useless row which then needs to be removed.

Is there a better way to do this?

Solution

Just initialize it with empty vectors:

df <- data.frame(Date=as.Date(character()),
                 File=character(), 
                 User=character(), 
                 stringsAsFactors=FALSE) 

Here’s an other example with different column types :

df <- data.frame(Doubles=double(),
                 Ints=integer(),
                 Factors=factor(),
                 Logicals=logical(),
                 Characters=character(),
                 stringsAsFactors=FALSE)

str(df)
> str(df)
'data.frame':   0 obs. of  5 variables:
 $ Doubles   : num 
 $ Ints      : int 
 $ Factors   : Factor w/ 0 levels: 
 $ Logicals  : logi 
 $ Characters: chr 

N.B. :

Initializing a data.frame with an empty column of the wrong type does not prevent further additions of rows having columns of different types.
This method is just a bit safer in the sense that you’ll have the correct column types from the beginning, hence if your code relies on some column type checking, it will work even with a data.frame with zero rows.

Answered By: Anonymous

Related Articles

  • In Pandas, how do I convert a number column to…
  • How do the PHP equality (== double equals) and…
  • Select DataFrame rows between two dates
  • Current time formatting with Javascript
  • Python sort_values (inplace=True) but not really?
  • Running a loop on multiple .txt files in one folder in R
  • SQL query return data from multiple tables
  • What are the undocumented features and limitations…
  • data.table vs dplyr: can one do something well the…
  • Combining items using XSLT Transform
  • Data structure for maintaining tabular data in memory?
  • Fix top buttons on scroll of list below
  • Replacing blank values (white space) with NaN in pandas
  • Convert Java Date to UTC String
  • Is it possible to apply CSS to half of a character?
  • Why Slime's debugger is not evaluating this specific…
  • Where and why do I have to put the "template" and…
  • Matching identical columns
  • What is your most productive shortcut with Vim?
  • Start redis-server with config file
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • WAVE file unexpected behaviour
  • Use of Jquery on scroll event
  • Best way to extract messy HTML tables using BeautifulSoup
  • How are zlib, gzip and zip related? What do they…
  • Smart way to truncate long strings
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • insert tables in dataframe with years from 2000 to…
  • Group array of objects by multiple keys using d3.groups
  • BigQuery: user metadata described by start date and…
  • How to append rows to an R data frame
  • Use of String.Format in JavaScript?
  • SDL_SetRenderTarget() hangs for a while if multiple…
  • Lua: Obtaining number of quarters and day of quarter
  • How to properly do JSON API GET requests and assign…
  • "Large data" workflows using pandas
  • How to handle Vue 2 memory usage for large data (~50…
  • Rails wrong number of arguments error when…
  • Reference to Object is lost somehow
  • Vuejs build checkbox dynamically from array
  • How do I test to see if a line of a .txt exists or…
  • How to concatenate cell values until it finds a…
  • What is an optional value in Swift?
  • javascript .replace and .trim not working in vuejs
  • How To Edit Date and Time Picker Vuejs Vuetify From…
  • ExpressJS How to structure an application?
  • Database development mistakes made by application developers
  • The definitive guide to form-based website authentication
  • flutter - add network images in a pdf while creating…
  • How do I count unique visitors to my site?
  • How to vertically align an image inside a div
  • What's the difference between eval, exec, and compile?
  • Python Pandas repeat the same number every 12 rows
  • How to export data to an excel file using PHPExcel
  • D3 chart integration into Vuejs
  • For-each over an array in JavaScript
  • how can I make this specific format with moment
  • How does PHP 'foreach' actually work?
  • Why does C++ code for testing the Collatz conjecture…
  • Dodged bar plot in R based on to columns with count…
  • Replace the UUIDs with Strings
  • For Loop on Lua
  • creating multiple frames in tkinter
  • Edge does not show div with Aurelia bindings which I…
  • What is an application binary interface (ABI)?
  • Memcached vs. Redis?
  • Usage of __slots__?
  • Why do git fetch origin and git fetch : behave differently?
  • Interrupt an earlier timeout event in Simpy
  • TypeError: Cannot read property 'webpackJsonp' of undefined
  • How can I manually compile a svelte component down…
  • Custom date picker in Vuetify
  • Ukkonen's suffix tree algorithm in plain English
  • Java string to date conversion
  • How to store standard error in a variable
  • Git Using Remote Branch
  • How to find Control in TemplateField of GridView?
  • Simultaneously merge multiple data.frames in a list
  • How do i arrange images inside a div?
  • Merge list of results into a single variable with Python
  • anime.js not targetting elements
  • Best practice multi language website
  • Blazor Can't Update UI
  • React after posting new password for user can't log in
  • What are the nuances of scope prototypal /…
  • The image I am adding as a button in Tkinter is not…
  • What is a NullReferenceException, and how do I fix it?
  • Filtering an object based on key, then constructing…
  • Active tab issue on page load HTML
  • jQuery Mobile: document ready vs. page events
  • Change column type in pandas
  • How to convert java.util.Date to java.sql.Date?
  • Switch statement for greater-than/less-than
  • Logging best practices
  • How to implement a basic iterative pushdown…
  • VBA get a list of files in folder and their tags (Keywords)
  • Polymer 1.0 'array-style' path accessors,…
  • Best approach to real time http streaming to HTML5…
  • What's the difference between Instant and LocalDateTime?
  • TypeScript metadata reflection references other…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Check whether a string is not null and not empty

Next Post:

LINQ’s Distinct() on a particular property

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error