How to add a column to a data frame

Use the $ Operator

df$new <- c(3, 3, 6, 7, 8, 12)

#define new column to add
new <- c(3, 3, 6, 7, 8)

#add column called 'new'
df$new <- 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

Use Brackets

df[‘new’] <- c(3, 3, 6, 7, 8, 12)

Use Cbind

df_new <- cbind(df, new)

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

#define new columns to add
new1 <- c(3, 3, 6, 7, 8)
new2 <- c(13, 14, 16, 17, 20) 

#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

Set column names

Use the colnames() function to specify the column names.

#create data frame
df <- data.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) <- c('a', 'b', 'c', 'd')

#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