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
Let me show #4 approach "By using "cbind" and "rename" that works for my case
df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
new_column = c(0, 0, 0)
df <- cbind(new_column, df)
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
Source: Stackoverflow.com