Data Frame Creation in R Programming Language

Rumman Ansari   Software Engineer   2023-03-24   5989 Share
☰ Table of Contents

Table of Content:


Data frames are used to store tabular data in R. They are an important type of object in R and are used in a variety of statistical modeling applications. Hadley Wickham’s package dplyr has an optimized set of functions designed to work efficiently with data frames.

Data frames are represented as a special type of list where every element of the list has to have the same length. Each element of the list can be thought of as a column and the length of each element of the list is the number of rows.

Unlike matrices, data frames can store different classes of objects in each column. Matrices must have every element be the same class (e.g. all integers or all numeric).

In addition to column names, indicating the names of the variables or predictors, data frames have a special attribute called row.names which indicate information about each row of the data frame.

Data frames are usually created by reading in a dataset using the read.table() or read.csv(). However, data frames can also be created explicitly with the data.frame() function or they can be coerced from other types of objects like lists.

Data frames can be converted to a matrix by calling data.matrix() . While it might seem that the as.matrix() function should be used to coerce a data frame to a matrix, almost always, what you want is the result of data.matrix().

 
> x <- data.frame(foo = 1:4, bar = c(T, T, F, F))
> x
foo bar
1 1 TRUE
2 2 TRUE
3 3 FALSE
4 4 FALSE
> nrow(x)
[1] 4
> ncol(x)
[1] 2

 

Names

R objects can havenames, which is very useful for writing readable code and self-describing objects. Here is an example of assigning names to an integer vector.

 
> x <- 1:3
> names(x)
NULL
> names(x) <- c("New York", "Seattle", "Los Angeles")
> x
New York Seattle Los Angeles
1 2 3
> names(x)
[1] "New York" "Seattle" "Los Angeles"

 

Lists can also have names, which is often very useful.

 
> x <- list("Los Angeles" = 1, Boston = 2, London = 3)
> x
$`Los Angeles`
[1] 1
$Boston
[1] 2
$London
[1] 3
> names(x)
[1] "Los Angeles" "Boston" "London"

 

Matrices can have both column and row names.

 
> m <- matrix(1:4, nrow = 2, ncol = 2)
> dimnames(m) <- list(c("a", "b"), c("c", "d"))
> m
c d
a 1 3
b 2 4

 

Column names and row names can be set separately using the colnames() and rownames() functions.

 
> colnames(m) <- c("h", "f")
> rownames(m) <- c("x", "z")
> m
h f
x 1 3
z 2 4

 

Note that for data frames, there is a separate function for setting the row names, the row.names() function. Also, data frames do not have column names, they just have names (like lists). So to set the column names of a data frame just use the names() function. Yes, I know its confusing. Here’s a quick summary:

Object Set column names  Set row names
data frame  names() row.names()
matrix colnames() rownames()

Example of Data Frame

> myvalues1 = c(348, -343, 937, 394, 124)
> myvalues2 = c(T, F, T, T, F)
> names = c("trial 1", "trial 2", "trial 3", "trial 4", "trial 5")
> dataframe1 = data.frame(myvalues1, myvalues2, row.names = names)

Get the Structure of the Data Frame

The structure of the data frame can be seen by using str() function.

> str(dataframe1)

Output

When we execute the above code, it produces the following result ?


'data.frame':	5 obs. of  2 variables:
 $ myvalues1: num  348 -343 937 394 124
 $ myvalues2: logi  TRUE FALSE TRUE TRUE FALSE

Summary of Data in Data Frame

The statistical summary and nature of the data can be obtained by applying summary() function.

 
> # Print the summary.
> print(summary(dataframe1))

Output

When we execute the above code, it produces the following result ?


   myvalues1    myvalues2      
 Min.   :-343   Mode :logical  
 1st Qu.: 124   FALSE:2        
 Median : 348   TRUE :3        
 Mean   : 292                  
 3rd Qu.: 394                  
 Max.   : 937  

Extract Data from Data Frame

Extract specific column from a data frame using column name.

 
> # Extract Specific columns.
> result <- data.frame(dataframe1$myvalues1)
> print(result)

Output

When we execute the above code, it produces the following result ?


  dataframe1.myvalues1
1                  348
2                 -343
3                  937
4                  394
5                  124

Extract the first two rows and then all columns

 
> # Extract first two rows.
> result <- dataframe1[1:2,]
> print(result)

Output

When we execute the above code, it produces the following result ?


        myvalues1 myvalues2
trial 1       348      TRUE
trial 2      -343     FALSE

Extract 3rd and 5th row with 1nd and 2th column

 
> # Extract 3rd and 5th row with 1nd and 2th column.
> result <- dataframe1[c(3,5),c(1,2)]
> print(result)

Output

When we execute the above code, it produces the following result ?


        myvalues1 myvalues2
trial 3       937      TRUE
trial 5       124     FALSE