How to Create a DataFrame in R

04.13.2021

DataFrames are a super powered matrix. Much of your data science work will be using data frames. In this article, we will learn how to create data frames in R.

The first way we can create a data frame in R is we can pass multiple vectors to the data.frame function. The vectors will be used as the columns.

ad.names = c("Google", "Facebook", "Twitter")
clicks = c(2000, 4000, 3000)

df = data.frame(ad.names, clicks)

print(df)

#    ad.names clicks
# 1   Google   2000
# 2 Facebook   4000
# 3  Twitter   3000

By default, the variable names will be used as the column names. We can specify the names when creating the data frame if we want.

df = data.frame(names=ad.names, clicks=clicks)

print(df)

#    names    clicks
# 1   Google   2000
# 2 Facebook   4000
# 3  Twitter   3000

We can also create a data frame from rows (other data frames). We can pass a list of rows to the rbind method which will bind together the rows into a data frame.

row1 = data.frame(name="Google", clicks="2000")
row2 = data.frame(name="Facebook", clicks="4000")
row3 = data.frame(name="Twitter", clicks="3000")

rbind(row1, row2, row3)


#    name    clicks
# 1   Google   2000
# 2 Facebook   4000
# 3  Twitter   3000