[r] How to add new column to an dataframe (to the front not end)?

How to add a new variable to an existing data frame, but I want to add to the front not end. eg. my dataframe is

b c d
1 2 3
1 2 3
1 2 3

I want to add a new variable a, so the dataframe will looks like

a b c d
0 1 2 3
0 1 2 3
0 1 2 3

This question is related to r dataframe

The answer is


If you want to do it in a tidyverse manner, try add_column from tibble, which allows you to specifiy where to place the new column with .before or .after parameter:

library(tibble)

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
add_column(df, a = 0, .before = 1)

#   a b c d
# 1 0 1 2 3
# 2 0 1 2 3
# 3 0 1 2 3

cbind inherents order by its argument order.

User your first column(s) as your first argument

cbind(fst_col , df)

  fst_col   df_col1   df_col2
1 0             0.2      -0.1
2 0             0.2      -0.1
3 0             0.2      -0.1
4 0             0.2      -0.1
5 0             0.2      -0.1

cbind(df, last_col)

  df_col1   df_col2  last_col
1 0.2      -0.1             0
2 0.2      -0.1             0
3 0.2      -0.1             0
4 0.2      -0.1             0
5 0.2      -0.1             0

The previous answers show 3 approaches

  1. By creating a new data frame
  2. By using "cbind"
  3. By adding column "a", and sort data frame by columns using column names or indexes

Let me show #4 approach "By using "cbind" and "rename" that works for my case

1. Create data frame

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))

2. Get values for "new" column

new_column = c(0, 0, 0)

3. Combine "new" column with existed

df <- cbind(new_column, df)

4. Rename "new" column name

colnames(df)[1] <- "a"


Use cbind e.g.

df <- data.frame(b = runif(6), c = rnorm(6))
cbind(a = 0, df)

giving:

> cbind(a = 0, df)
  a         b          c
1 0 0.5437436 -0.1374967
2 0 0.5634469 -1.0777253
3 0 0.9018029 -0.8749269
4 0 0.1649184 -0.4720979
5 0 0.6992595  0.6219001
6 0 0.6907937 -1.7416569

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
df
##   b c d
## 1 1 2 3
## 2 1 2 3
## 3 1 2 3

df <- data.frame(a = c(0, 0, 0), df)
df
##   a b c d
## 1 0 1 2 3
## 2 0 1 2 3
## 3 0 1 2 3

Add column "a"

> df["a"] <- 0
> df
  b c d a
1 1 2 3 0
2 1 2 3 0
3 1 2 3 0

Sort by column using colum name

> df <- df[c('a', 'b', 'c', 'd')]
> df
  a b c d
1 0 1 2 3
2 0 1 2 3
3 0 1 2 3

Or sort by column using index

> df <- df[colnames(df)[c(4,1:3)]]
> df
  a b c d
1 0 1 2 3
2 0 1 2 3
3 0 1 2 3