Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert columns by column index (unaltered column order)

Tags:

r

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 column index numbers of the headers containing "2" by:

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

I want to add two extra columns named "A2.1","A2.2","B2.1", "B2.2", etc. (or an alternative nomenclature that allows me to distinguish them) next to the columns with index 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 issue in the following post: Insert columns by column index

However, in the resulting data frame the columns are alphabetically ordered, and I do not want that.

Does anybody know how to fix the ordering issue?

Many thanks in advance!

like image 250
David Avatar asked Mar 23 '26 06:03

David


1 Answers

I would approach this differently. Instead of replicating the columns, I will just subset the columns I need several times (3 times in this case). This way the order of the columns will be stored.

Creating the subsetting 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

Subsetting the columns 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
like image 138
David Arenburg Avatar answered Mar 24 '26 20:03

David Arenburg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!