Insert columns by column index (unchanged column order)

Given the following data frame:

> header = c("A1","A2","A3","B1","B2","B3","AB1", "AB2", "AB3")
> df = matrix(c(0,0,0,0,0,0,0,0,0),nrow = 1)
> colnames(df) = header
> df
     A1 A2 A3 B1 B2 B3 AB1 AB2 AB3
[1,]  0  0  0  0  0  0   0   0   0

      

I know the index numbers of the header columns containing "2":

> index2 = grep("2", colnames(df))
> index2
[1] 2 5 8

      

I want to add two additional columns named "A2.1", "A2.2", "B2.1", "B2.2", etc. (or an alternative nomenclature that allows me to differentiate between the two) next to columns at indices 2.5 and 8, so that:

     A1 A2 A2.1 A2.2 A3 B1 B2 B2.1 B2.2 B3 AB1 AB2 AB2.1 AB2.2 AB3
[1,]  0  0  0  0  0  0  0  0  0    0    0    0   0     0     0   0

      

I solved a similar problem in the following post: Insert Columns by Column Index

However, in the resulting data frame, the columns are alphabetically ordered and I don't want that.

Does anyone know how to fix the ordering problem?

Thank you very much in advance!

+3


source to share


1 answer


I would have acted differently. Instead of replicating the columns, I'll just multiply the columns that I need multiple times (3 times in this case). This way, the order of the columns will be preserved.

Creating a subset index

indx <- unlist(lapply(1:ncol(df), function(x) if(x %in% index2) rep(x, 3) else x))
## [1] 1 2 2 2 3 4 5 5 5 6 7 8 8 8 9

      



Column substitution and renaming

df1 <- df[, indx, drop = FALSE]
colnames(df1) <- make.unique(colnames(df1))
df1
#      A1 A2 A2.1 A2.2 A3 B1 B2 B2.1 B2.2 B3 AB1 AB2 AB2.1 AB2.2 AB3
# [1,]  0  0    0    0  0  0  0    0    0  0   0   0     0     0   0

      

+4


source







All Articles