I have a data frame that has columns a, b, and c. I\'d like to add a new column d between b and c.
I know I could just add d at the end by using cbind but h
Here's a quick and dirty way of inserting a column in a specific position on a data frame. In my case, I have 5 columns in the original data frame: c1, c2, c3, c4, c5
and I will insert a new column c2b
between c2
and c3
.
1) Let's first create the test data frame:
> dataset <- data.frame(c1 = 1:5, c2 = 2:6, c3=3:7, c4=4:8, c5=5:9)
> dataset
c1 c2 c3 c4 c5
1 1 2 3 4 5
2 2 3 4 5 6
3 3 4 5 6 7
4 4 5 6 7 8
5 5 6 7 8 9
2) Add the new column c2b
at the end of our data frame:
> dataset$c2b <- 10:14
> dataset
c1 c2 c3 c4 c5 c2b
1 1 2 3 4 5 10
2 2 3 4 5 6 11
3 3 4 5 6 7 12
4 4 5 6 7 8 13
5 5 6 7 8 9 14
3) Reorder the data frame based on column indexes. In my case, I want to insert the new column (6) between existing columns 2 and 3. I do that by addressing the columns on my data frame using the vector c(1:2, 6, 3:5)
which is equivalent to c(1, 2, 6, 3, 4, 5)
.
> dataset <- dataset[,c(1:2, 6, 3:5)]
> dataset
c1 c2 c2b c3 c4 c5
1 1 2 10 3 4 5
2 2 3 11 4 5 6
3 3 4 12 5 6 7
4 4 5 13 6 7 8
5 5 6 14 7 8 9
There!
Here is a an example of how to move a column from last to first position. It combines [
with ncol
. I thought it would be useful to have a very short answer here for the busy reader:
d = mtcars
d[, c(ncol(d), 1:(ncol(d)-1))]
You can reorder the columns with [, or present the columns in the order that you want.
d <- data.frame(a=1:4, b=5:8, c=9:12)
target <- which(names(d) == 'b')[1]
cbind(d[,1:target,drop=F], data.frame(d=12:15), d[,(target+1):length(d),drop=F])
a b d c
1 1 5 12 9
2 2 6 13 10
3 3 7 14 11
4 4 8 15 12
Presuming that c
always immediately follows b
, this code will add a column after b
no matter where b
is in your data.frame.
> test <- data.frame(a=1,b=1,c=1)
> test
a b c
1 1 1 1
> bspot <- which(names(test)=="b")
> data.frame(test[1:bspot],d=2,test[(bspot+1):ncol(test)])
a b d c
1 1 1 2 1
Or possibly more naturally:
data.frame(append(test, list(d=2), after=match("b", names(test))))
You would like to add column z to the old data frame (old.df) defined by columns x and y.
z = rbinom(1000, 5, 0.25)
old.df <- data.frame(x = c(1:1000), y = rnorm(1:1000))
head(old.df)
Define a new data frame called new.df
new.df <- data.frame(x = old.df[,1], z, y = old.df[,2])
head(new.df)