Home » How to Add Multiple Columns to Data Frame in R

How to Add Multiple Columns to Data Frame in R

by Erma Khan

You can use the following methods to add multiple columns to a data frame in R:

Method 1: Add Multiple Columns to data.frame Object

df[c('new_col1', 'new_col2', 'new_col3')] 

Method 2: Add Multiple Columns to data.table Object

library(data.table)

df[ , ':='(new_col1 = new_col1, new_col2 = new_col2,  new_col3 = new_col3)] 

The following examples show how to use each method in practice.

Example 1: Add Multiple Columns to data.frame Object

Suppose we have the following data frame in R:

#define data frama
df frame(A=c(4, 8, 10, 2, 15, 12, 7, 22),
                 B=c(6, 3, 9, 7, 6, 8, 14, 10),
                 C=c(10, 9, 4, 4, 3, 7, 10, 11))

#view data frame
df

   A  B  C
1  4  6 10
2  8  3  9
3 10  9  4
4  2  7  4
5 15  6  3
6 12  8  7
7  7 14 10
8 22 10 11

We can use the following syntax to add three new columns to the data frame that each contain NA values:

#add three new columns to data frame
df[c('D', 'E', 'F')] #view updated data frame
df

   A  B  C  D  E  F
1  4  6 10 NA NA NA
2  8  3  9 NA NA NA
3 10  9  4 NA NA NA
4  2  7  4 NA NA NA
5 15  6  3 NA NA NA
6 12  8  7 NA NA NA
7  7 14 10 NA NA NA
8 22 10 11 NA NA NA

Three new columns with all NA values have been added to the data frame.

Example 2: Add Multiple Columns to data.table Object

Suppose we have the following data table in R:

library(data.table)

#create data table
dt table(A=c(4, 8, 10, 2, 15, 12, 7, 22),
                 B=c(6, 3, 9, 7, 6, 8, 14, 10),
                 C=c(10, 9, 4, 4, 3, 7, 10, 11))

#view data table
dt

    A  B  C
1:  4  6 10
2:  8  3  9
3: 10  9  4
4:  2  7  4
5: 15  6  3
6: 12  8  7
7:  7 14 10
8: 22 10 11

We can use the following syntax to add two new columns to the data table:

#define two columns to add
D = c(4, 5, 5, 4, 7, 8, 12, 10)
E = c(2, 2, 5, 7, 6, 5, 10, 13)

#add two columns to data table
dt[ , ':='(D = D, E = E)]

#view updated data table
dt

    A  B  C  D  E
1:  4  6 10  4  2
2:  8  3  9  5  2
3: 10  9  4  5  5
4:  2  7  4  4  7
5: 15  6  3  7  6
6: 12  8  7  8  5
7:  7 14 10 12 10
8: 22 10 11 10 13

Notice that two new columns have been added to the data table.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Add Column to Data Frame Based on Other Columns in R
How to Sort by Multiple Columns in R
How to Reorder Columns in R

Related Posts