Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new variable to specific position in dataframe

Tags:

r

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?

like image 795
Diegoal Avatar asked Feb 12 '13 12:02

Diegoal


People also ask

How do you add a new variable to a data frame?

In this example, instead of using the assign() method, we use square brackets ([]) to create a new variable or column for an existing Dataframe. The syntax goes like this: dataframe_name['column_name'] = data column_name is the name of the new column to be added in our dataframe.

How do you add a column to the left of a DataFrame?

In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.


2 Answers

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"))
like image 82
sebastian-c Avatar answered Sep 23 '22 21:09

sebastian-c


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

like image 30
Alejandro Ochoa Avatar answered Sep 23 '22 21:09

Alejandro Ochoa