How do you add a new column to a data frame in R?

  1. Using the $ symbol:
df <- data.frame(col_1=10:13, col_2=c("a", "b", "c", "d"))
print(df)
​
df$col_3 <- c(5, 1, 18, 16)
print(df)Powered By 

Output:

  col_1 col_2
1    10     a
2    11     b
3    12     c
4    13     d
  col_1 col_2 col_3
1    10     a     5
2    11     b     1
3    12     c    18
4    13     d    16Powered By 
  1. Using square brackets:
df <- data.frame(col_1=10:13, col_2=c("a", "b", "c", "d"))
print(df)
​
df["col_3"] <- c(5, 1, 18, 16)
print(df)Powered By 

Output:

  col_1 col_2
1    10     a
2    11     b
3    12     c
4    13     d
  col_1 col_2 col_3
1    10     a     5
2    11     b     1
3    12     c    18
4    13     d    16Powered By 
  1. Using the cbind() function:
df <- data.frame(col_1=10:13, col_2=c("a", "b", "c", "d"))
print(df)
​
df <- cbind(df, col_3=c(5, 1, 18, 16))
print(df)Powered By 

Output:

 col_1 col_2
1    10     a
2    11     b
3    12     c
4    13     d
  col_1 col_2 col_3
1    10     a     5
2    11     b     1
3    12     c    18
4    13     d    16Powered By 

In each of the three cases, we can assign a single value or a vector or calculate the new column based on the existing columns of that data frame or other data frames.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *