Add (insert) a column between two columns in a data.frame
I would suggest you to use the function add_column()
from the tibble
package.
library(tibble)
dataset <- data.frame(a = 1:5, b = 2:6, c=3:7)
add_column(dataset, d = 4:8, .after = 2)
Note that you can use column names instead of column index :
add_column(dataset, d = 4:8, .after = "b")
Or use argument .before
instead of .after
if more convenient.
add_column(dataset, d = 4:8, .before = "c")
Add in your new column:
df$d <- list/data
Then you can reorder them.
df <- df[, c("a", "b", "d", "c")]
You can reorder the columns with [, or present the columns in the order that you want.
d <- data.frame(a=1:4, b=5:8, c=9:12)
target <- which(names(d) == 'b')[1]
cbind(d[,1:target,drop=F], data.frame(d=12:15), d[,(target+1):length(d),drop=F])
a b d c
1 1 5 12 9
2 2 6 13 10
3 3 7 14 11
4 4 8 15 12
Presuming that c
always immediately follows b
, this code will add a column after b
no matter where b
is in your data.frame.
> test <- data.frame(a=1,b=1,c=1)
> test
a b c
1 1 1 1
> bspot <- which(names(test)=="b")
> data.frame(test[1:bspot],d=2,test[(bspot+1):ncol(test)])
a b d c
1 1 1 2 1
Or possibly more naturally:
data.frame(append(test, list(d=2), after=match("b", names(test))))