How to Apply the data.frame Function in R (2 Examples)

On this page you’ll learn how to create data frames using the data.frame function in R programming.

Example 1: Constructing a Data Frame Using the data.frame() Function

my_df1 <- data.frame(A = 10:5,      # Create a data frame object
                     B = LETTERS[1:6],
                     C = c("x", "y", "x", "x", "y", "x"))
my_df1
#    A B C
# 1 10 A x
# 2  9 B y
# 3  8 C x
# 4  7 D x
# 5  6 E y
# 6  5 F x

Example 2: Converting a Matrix to a Data Frame Using the data.frame() Function

my_mat <- matrix(1:20, ncol = 4)    # Create a matrix object
my_mat
#      [,1] [,2] [,3] [,4]
# [1,]    1    6   11   16
# [2,]    2    7   12   17
# [3,]    3    8   13   18
# [4,]    4    9   14   19
# [5,]    5   10   15   20
my_df2 <- data.frame(my_mat)        # Convert matrix to data.frame class
my_df2
#   X1 X2 X3 X4
# 1  1  6 11 16
# 2  2  7 12 17
# 3  3  8 13 18
# 4  4  9 14 19
# 5  5 10 15 20

Leave a Reply

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

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