Insert a new column between two columns

Post date: Apr 2, 2014 8:12:55 AM

If you want to insert a new column after a certain column, here is a convenient function to do so.

For other ideas, refer to this thread.

# ===================================== # Insert a column in a dataframe after  # column "abc" or n-th column  # ===================================== insertAfter <- function(df,x,colName,newColName) {   if (class(colName)=='numeric') {     target <- colName   } else {     target <- which(names(df) == as.character(colName))[1]   }     if (target==0) {     # put x at the first column     out <- cbind(x,df)   } else {     if (target>=ncol(df)) {       # just append it to the end       out <- cbind(df,x)     } else {       out <- cbind(df[,1:target,drop=F], data.frame(x), df[,(target+1):ncol(df),drop=F])     }   }     names(out)[target+1] <- newColName     return(out) }     # ================================================ # Demo # ================================================ df <- data.frame(a=1:4, b=5:8, c=9:12) x <- data.frame('new'=c(1,0,1,0))   > df   a b  c 1 1 5  9 2 2 6 10 3 3 7 11 4 4 8 12   > x   new 1   1 2   0 3   1 4   0       > insertAfter(df,x,1,"yeehah")   a yeehah b  c 1 1      1 5  9 2 2      0 6 10 3 3      1 7 11 4 4      0 8 12 > insertAfter(df,x,'a',"yeehah")   a yeehah b  c 1 1      1 5  9 2 2      0 6 10 3 3      1 7 11 4 4      0 8 12 > insertAfter(df,x,0,"yeehah")   yeehah a b  c 1      1 1 5  9 2      0 2 6 10 3      1 3 7 11 4      0 4 8 12 > insertAfter(df,x,'c',"yeehah") a b  c yeehah   1 1 5  9      1 2 2 6 10      0 3 3 7 11      1 4 4 8 12      0 > insertAfter(df,x,'b',"yeehah")   a b yeehah  c 1 1 5      1  9 2 2 6      0 10 3 3 7      1 11 4 4 8      0 12 > insertAfter(df,x,3,"yeehah")   a b  c yeehah 1 1 5  9      1 2 2 6 10      0 3 3 7 11      1 4 4 8 12      0
Created by Pretty R at inside-R.org

---------