How to Create DataFrame in R Using Examples

Creating DataFrame in R is very easy.

How to create an empty dataframe in R

To create dataframe, we can use data.frame method.

In [1]:
df = data.frame()

The above will create an empty dataframe. Let us check if it is dataframe.

In [2]:
is.data.frame(df)
TRUE

Let us add some dummy data to our dataframe.

We can index row and columns using index. For example df[1,1] means at row 1 and column 1.

In [3]:
df[1,1] = c(1)
In [4]:
head(df)
A data.frame: 1 × 1
V1
<dbl>
11

Let us add another value. Let us do df[2,] that means row 2 and all the columns. In our dataframe, we have only one column.

In [5]:
df[2,] = c(2)
In [6]:
head(df)
A data.frame: 2 × 1
V1
<dbl>
11
22

Our dataframe has two rows now and column name is V1 which is set by default in R. Let us change the name of column.

How to change column name in R

Let us print the existing colnames first.

In [7]:
colnames(df)
'V1'

Let us change column name to "Number".

In [8]:
colnames(df) <- c('Number')
In [9]:
head(df)
A data.frame: 2 × 1
Number
<dbl>
11
22

How to add new column in dataframe in R

Let us first prepare our data. Since our existing dataframe has two values, we will create an entry with two values.

In [10]:
names <- c("a","b")

To add this to our dataframe, do following.

In [11]:
df$alphabet <- names

df$alphabet, this will add column name "alphabet" in our dataframe if it doesn't exist and assign values a and b. Let us check now.

In [12]:
head(df)
A data.frame: 2 × 2
Numberalphabet
<dbl><chr>
11a
22b

How to initialize dataframe with data in R

We can also build our dataframe directly by giving it column names and values in one shot as shown below.

In [13]:
df1 <- data.frame(name=c("John","Alex"),profession=c("Engineer","Director"))
In [14]:
head(df1)
A data.frame: 2 × 2
nameprofession
<fct><fct>
1JohnEngineer
2AlexDirector

Let us add another column place_of_living in our dataframe df1.

In [15]:
place_of_living <- c('California','New York')

Now we can bind our column to the dataframe using cbind.

In [16]:
cbind(df1,place_of_living)
A data.frame: 2 × 3
nameprofessionplace_of_living
<fct><fct><fct>
JohnEngineerCalifornia
AlexDirectorNew York

As we can see, new column "place_of_living" is added to our dataframe. Note you can also use df1$place_of_living to add column.

Wrap Up!

This sums up my brief tutorial about creating dataframes in R.