How to create a data frame from scratch (in R)
Task
Sometimes it is useful to create a small table of data directly in code, without first needing to store the data in a file and load it from there. This can be useful for creating small tables for testing purposes, or for creating small lookup tables that hold abbreviations, IDs, etc. What’s the easiest way to build such a table?
Solution
In R, the data.frame
function can be used to build data frames.
Each column in your data should be a separate parameter, with its name provided,
followed by an equals sign, followed by the vector of column contents,
as shown in the example below.
1
2
3
4
5
6
data <- data.frame(
last.name = c( 'Potter', 'Weasley', 'Granger', 'Malfoy' ),
first.name = c( 'Harry', 'Ron', 'Hermione', 'Draco' ),
house = c( 'Griffindor', 'Griffindor', 'Griffindor', 'Slytherin' )
)
data
1
2
3
4
5
last.name first.name house
1 Potter Harry Griffindor
2 Weasley Ron Griffindor
3 Granger Hermione Griffindor
4 Malfoy Draco Slytherin
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)