Add Column to R Data Frame

To add a new column to R Data Frame, use dollar sign $ as shown in the following syntax.

</>
Copy
 mydataframe$newcolumn <- vector_name

In this tutorial, we will learn how to add a column to a Data Frame in R programming.

where

  • mydataframe is the data frame to which we shall add a new column.
  • newcolumn is the name of the new column.
  • vector_name is the vector containing the values of new column.

Examples

1 – Add Column to R Data Frame

In this example, we will create a data frame DF1 and add a column to the data frame.

</>
Copy
> DF1 = data.frame(V1= c(1, 5, 14, 23, 54), V2= c(9, 15, 85, 3, 42), V3= c(9, 7, 42, 87, 16))
> DF1
  V1 V2 V3
1  1  9  9
2  5 15  7
3 14 85 42
4 23  3 87
5 54 42 16
> DF1$V4 = c(55, 66, 85, 12, 21)
> DF1
  V1 V2 V3 V4
1  1  9  9 55
2  5 15  7 66
3 14 85 42 85
4 23  3 87 12
5 54 42 16 21
>

Column V4 is successfully added to the data frame.

Example 2 – Add Column (with lesser length) to R Data Frame

In this example, we will create a data frame DF1 and add a column with number of rows less than the existing number of rows in the data frame.

</>
Copy
> DF1 = data.frame(V1= c(1, 5, 14, 23, 54), V2= c(9, 15, 85, 3, 42), V3= c(9, 7, 42, 87, 16))
> DF1
  V1 V2 V3
1  1  9  9
2  5 15  7
3 14 85 42
4 23  3 87
5 54 42 16
> DF1$V4 = c(55, 66, 85, 12)
Error in `$<-.data.frame`(`*tmp*`, V4, value = c(55, 66, 85, 12)) : 
  replacement has 4 rows, data has 5
> 

You will get an error “replacement has 4rows, data has 5”.