How to Add an Empty Column to a Data Frame in R

To add an empty column to a data frame in R, you can use the add_column() function from the tidyverse library. This function allows you to add a column to a data frame with a given name and a default value, such as NA for an empty column. This is a useful way to add additional columns to a data frame in order to store additional information. Additionally, you can use the mutate() function from the same library to assign values to the empty column.


You can use the following basic syntax to add one or more empty columns to a data frame in R:

#add one empty column called 'column1' to data frame
df[ , 'column1'] <- NA

#add several empty columns to data frame
empty_cols <- c('column1', 'column2', 'column3')
df[ , empty_cols] <- NA

The following examples show how to use this syntax in practice.

Example 1: Add One Empty Column to Data Frame

The following code shows how to add one empty column to a data frame in R:

#create data frame
df <- data.frame(team=c('Mavs', 'Mavs', 'Spurs', 'Nets'),
                 points=c(99, 90, 84, 96),
                 assists=c(22, 19, 16, 20))

#view data frame
df

   team points assists
1  Mavs     99      22
2  Mavs     90      19
3 Spurs     84      16
4  Nets     96      20

#add new empty column
df[ , 'blocks'] <- NA

#view updated data frame
df

   team points assists blocks
1  Mavs     99      22     NA
2  Mavs     90      19     NA
3 Spurs     84      16     NA
4  Nets     96      20     NA

Example 2: Add Multiple Empty Columns to Data Frame

The following code shows how to add multiple empty columns to a data frame in R:

#create data frame
df <- data.frame(team=c('Mavs', 'Mavs', 'Spurs', 'Nets'),
                 points=c(99, 90, 84, 96),
                 assists=c(22, 19, 16, 20))

#view data frame
df

   team points assists
1  Mavs     99      22
2  Mavs     90      19
3 Spurs     84      16
4  Nets     96      20

#define names of empty columns to add
empty_cols <- c('blocks', 'rebounds', 'steals')

#add multiple empty columns
df[ , empty_cols] <- NA

#view updated data frame
df

   team points assists blocks rebounds steals
1  Mavs     99      22     NA       NA     NA
2  Mavs     90      19     NA       NA     NA
3 Spurs     84      16     NA       NA     NA
4  Nets     96      20     NA       NA     NA

The following tutorials explain how to create other empty objects in R:

x