Home » How to Add a Column to a Data Frame in R (With Examples)

How to Add a Column to a Data Frame in R (With Examples)

by Tutor Aspire

There are three common ways to add a new column to a data frame in R:

1. Use the $ Operator

df$new 

2. Use Brackets

df['new'] 

3. Use Cbind

df_new cbind(df, new)

This tutorial provides examples of how to use each of these methods in practice using the following data frame:

#create data frame
df frame(a = c('A', 'B', 'C', 'D', 'E'),
                 b = c(45, 56, 54, 57, 59))

#view data frame
df

  a  b
1 A 45
2 B 56
3 C 54
4 D 57
5 E 59

Example 1: Use the $ Operator

The following code shows how to add a column to a data frame by using the $ operator:

#define new column to add
new 
#add column called 'new'
df$new 
#view new data frame
df 

  a  b new
1 A 45   3
2 B 56   3
3 C 54   6
4 D 57   7
5 E 59   8

Example 2: Use Brackets

The following code shows how to add a column to a data frame by using brackets:

#define new column to add
new 
#add column called 'new'
df['new'] 
#view new data frame
df 

  a  b new
1 A 45   3
2 B 56   3
3 C 54   6
4 D 57   7
5 E 59   8

Example 3: Use Cbind

The following code shows how to add a column to a data frame by using the cbind function, which is short for column-bind:

#define new column to add
new 

#add column called 'new'
df_new cbind(df, new)

#view new data frame
df_new

  a  b new
1 A 45   3
2 B 56   3
3 C 54   6
4 D 57   7
5 E 59   8

You can actually use the cbind function to add multiple new columns at once:

#define new columns to add
new1 
#add columns called 'new1' and 'new2'
df_new cbind(df, new1, new2)

#view new data frame
df_new

  a  b new1 new2
1 A 45    3   13
2 B 56    3   14
3 C 54    6   16
4 D 57    7   17
5 E 59    8   20

Bonus: Set Column Names

After adding one or more columns to a data frame, you can use the colnames() function to specify the column names of the new data frame:

#create data frame
df frame(a = c('A', 'B', 'C', 'D', 'E'),
                 b = c(45, 56, 54, 57, 59),
                 new1 = c(3, 3, 6, 7, 8),
                 new2 = c(13, 14, 16, 17, 20))

#view data frame
df

  a  b new1 new2
1 A 45    3   13
2 B 56    3   14
3 C 54    6   16
4 D 57    7   17
5 E 59    8   20

#specify column names
colnames(df) #view data frame
df

  a  b c  d
1 A 45 3 13
2 B 56 3 14
3 C 54 6 16
4 D 57 7 17
5 E 59 8 20

You can find more R tutorials here.

You may also like