7

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?

micstr
  • 5,080
  • 8
  • 48
  • 76
Diegoal
  • 329
  • 2
  • 11

2 Answers2

10

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"))
Community
  • 1
  • 1
sebastian-c
  • 15,057
  • 3
  • 47
  • 93
1
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 the variable at the end of the data.frame and then using an indicator vector signaling how to reorder the columns. ind is just a vector of numbers

Alejandro Ochoa
  • 238
  • 1
  • 8
  • Thank you for your answer! I have (and most of us do have) a data frame with more than only a few variables, so putting in every column name or number manually would be too much effort! However, your code should be adjusted as follows: `(ncol(data)-1)`. If you forget the extra brackets, column A gets a copy A.1. – Poza Mar 22 '21 at 16:04