Add Empty Column to Data Frame in R (2 Examples)
In this tutorial, I’ll demonstrate how to create a new empty variable in a data frame in the R programming language.
The tutorial contains these contents:
You’re here for the answer, so let’s get straight to the exemplifying R code!
Creation of Example Data
First, I need to create some data that we can use in the examples later on:
data <- data.frame(x1 = 1:5, # Create example data frame x2 = letters[1:5], x3 = 2:6) data # Print example data frame
Have a look at the table that has been returned after running the previous code. It shows that our exemplifying data comprises five rows and three columns. The variables x1 and x3 are integers and the column x2 has the character data type.
Example 1: Add New Column Containing Empty Character Strings
In Example 1, I’ll demonstrate how to add a new empty variable to a data frame that contains blank character strings.
For this task, we can use the R code below:
data$new1 <- "" # Add empty character string data # Print updated data frame
After running the previous R syntax the updated data frame shown in Table 2 has been created. As you can see, we have added a new variable called new1 that consists only of empty characters.
Example 2: Add New Column Containing NA Values
In this example, I’ll show how to add a new column that contains only NA values to a data frame.
Consider the R code below:
data$new2 <- NA # Add NA column data # Print updated data frame
As shown in Table 3, we have created a new version of our data frame that contains another column called new2 that consists of of NA values only.
Video, Further Resources & Summary
In case you need further info on the contents of this article, I recommend having a look at the following video on my YouTube channel. I show the topics of this tutorial in the video:
In addition, you might want to read the related R programming tutorials that I have published on my website. I have published numerous tutorials that are related to the creation of a new empty variable in a data frame already.
- Append to Data Frame in Loop in R
- Add New Column to Data Frame in R
- Add Row to Empty Data Frame in R
- Data Manipulation in R
- All R Programming Tutorials
To summarize: In this tutorial, I have illustrated how to append an empty variable to a data frame in the R programming language. If you have any further questions, let me know in the comments section below. Furthermore, please subscribe to my email newsletter for updates on new tutorials.