Add a new column between other dataframe columns

dataframe, r

Solution

In 2 steps, you can reorder the columns:

dat$C <- NA
dat <- dat[, c("A", "C", "B")]
         A  C          B
1  0.596068 NA -0.7783724
2 -1.464656 NA -0.8425972

You can also use `append`

dat <- data.frame(A = rnorm(2), B = rnorm(2))
as.data.frame(append(dat, list(C = NA), after = 1))

           A   C          B
1 -0.7046408  NA  0.2117638
2  0.8402680  NA -2.0109721

Problem

I want to add a new column with "NA"s in my dataframe: ``` A B 1 14379 32094 2 151884 174367 3 438422 449382 ``` But I need it to be located between col. A and B, like this: ``` A C B 1 14379 NA 32094 2 151884 NA 174367 3 438422 NA 449382 ``` I know how to add col. C after col. B, but that is not helpful to me... Anyone know how to do it?

Original source

Related problems