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'] #add several empty columns to data frame empty_cols
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 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'] #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 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 #add multiple empty columns df[ , empty_cols] #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
Additional Resources
The following tutorials explain how to create other empty objects in R:
How to Create an Empty Data Frame in R
How to Create an Empty Matrix in R
How to Create an Empty Vector in R
How to Create an Empty List in R (With Examples)