Diegoal Diegoal - 3 months ago 12
R Question

Add new variable to specific position in dataframe

I have a DF where I want to add a new variable called "B" into the 2nd position.

A C D
1 1 5 2
2 3 3 7
3 6 2 3
4 6 4 8
5 1 1 2


Anyone have an idea?

Answer

The easiest way would be to add the columns you want and then reorder them:

dat$B <- 1:5
newdat <- dat[, c("A", "B", "C", "D")]

Another way:

newdat <- cbind(dat[1], B=1:5, dat[,2:3])

If you're concerned about overhead, perhaps a data.table solution? (With help from this answer):

library(data.table)
dattable <- data.table(dat)
dattable[,B:=1:5]
setcolorder(dattable, c("A", "B", "C", "D"))
Comments