Open In App

How to Add an Empty Column to DataFrame in R?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to add an empty column to the dataframe in R Programming Language.

Add One Empty Column to dataframe

Here we are going to add an empty column to the dataframe by assigning column values as NA.

Syntax:

dataframe[ , 'column_name'] = NA

where,

  • dataframe  is the input dataframe
  • column_name is the new column name

Example: R program to create a dataframe with 3 columns and add an empty column

R




# create a dataframe with 4 rows and 3 columns
data = data.frame(marks1=c('90', '78', '89', '76'),
                  marks2=c('92', '68', '78', '96'),
                  marks3=c('90', '78', '89', '76'))
 
# add an empty column named empty_column
data[, 'empty_column'] = NA
 
# display
print(data)


Output:

Add Multiple Empty Columns to dataframe

We can add multiple columns with empty values in dataframe by passing column names in c() function

Syntax:

data[,c('column_name1',column_name2',............,'column_name n')]

Example: R program to add 4 empty columns

R




# create a dataframe with 4 rows and 3 columns
data = data.frame(marks1=c('90', '78', '89', '76'),
                  marks2=c('92', '68', '78', '96'),
                  marks3=c('90', '78', '89', '76'))
 
# add 4 empty columns
data[, c('empty1', 'empty2', 'empty3', 'empty4')] = NA
 
# display
print(data)


Output:



Last Updated : 15 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads