How to Make a Data Frame in the R Programming Language (3 Examples)

In this article you’ll learn how to construct a data frame in R programming.

Example 1: How to Create an Empty Data Frame

df_A <- data.frame(col1 = numeric(),                   # Create empty data frame
                   col2 = character(),
                   col3 = numeric(),
                   col4 = factor(),
                   col5 = integer())
df_A
# [1] col1 col2 col3 col4 col5
# <0 rows> (or 0-length row.names)

Example 2: How to Create a Data Frame with Values

df_B <- data.frame(col1 = c("a", "c", "a", "b", "b"),  # Create data frame from scratch
                   col2 = 5:1,
                   col3 = "yo")
df_B
#   col1 col2 col3
# 1    a    5   yo
# 2    c    4   yo
# 3    a    3   yo
# 4    b    2   yo
# 5    b    1   yo

Example 3: How to Create a Data Frame based on Vectors

col1 <- 10:16                                          # Create four different vector objects
col2 <- c(7, 5, 5, 2, 2, 6, 8)
col3 <- LETTERS[1:7]
col4 <- 100
df_C <- data.frame(col1,                               # Create data frame from vectors
                   col2,
                   col3,
                   col4)
df_C
#   col1 col2 col3 col4
# 1   10    7    A  100
# 2   11    5    B  100
# 3   12    5    C  100
# 4   13    2    D  100
# 5   14    2    E  100
# 6   15    6    F  100
# 7   16    8    G  100

Related Tutorials & Further Resources

Have a look at the following list of R programming tutorials. They discuss topics such as variables, ggplot2, and graphics in R.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top