Add a new variable to a specific position in the dataframe

I have a DF where I want to add a new variable called "B" to the second 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?

+5
source share
2 answers

The easiest way is to add the necessary columns, and then change their order:

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 are worried about overhead, maybe a solution data.table? (Using this answer ):

library(data.table)
dattable <- data.table(dat)
dattable[,B:=1:5]
setcolorder(dattable, c("A", "B", "C", "D"))
+7
source
dat$B <- 1:5 
ind <- c(1:which(names(data) == "A"),ncol(data),(which(names(data) == "A")+1):ncol(data)-1)
data <- data[,ind]

Create a variable at the end of the data.frame, and then use an indicator light that signals how to reorder the columns. ind is just a vector of numbers

0
source

All Articles