df = matrix(c(0,0,0,0,0,0),nrow ...">

Insert Columns by Column Index

Given the following data frame:

> header = c("A1","A2","A3","B1","B2","B3")
> df = matrix(c(0,0,0,0,0,0),nrow = 1)
> colnames(df) = header
> df
     A1 A2 A3 B1 B2 B3
[1,]  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

      

I want to add two additional columns named "A2.1", "A2.2" and "B2.1", "B2.2" next to the columns with indexes 2 and 5 so that:

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

      

Ho can I do this?

Thank you very much in advance!

+1


source to share


2 answers


Assuming you want to insert columns based on "index2", one parameter is



df1 <- cbind(df, do.call(cbind,
          replicate(2,df[,index2, drop=FALSE], simplify=FALSE)))
df2 <- df1[,order(colnames(df1)), drop=FALSE]
colnames(df2) <- make.unique(colnames(df2))
df2
#     A1 A2 A2.1 A2.2 A3 B1 B2 B2.1 B2.2 B3
#[1,]  0  0    0    0  0  0  0    0    0  0

      

+4


source


You can try something like this:

set.seed(1234)
df <- data.frame(matrix(runif(100),ncol=5))
colnames(df) <- LETTERS[1:ncol(df)]
B.1 <- runif(20)
df <- cbind(df,B.1)
df <- df[,order(colnames(df))]
#> head(df)
#          A          B        B.1         C          D         E
#1 0.1137034 0.31661245 0.03545673 0.5533336 0.86483383 0.9264005
#2 0.6222994 0.30269337 0.56507611 0.6464061 0.04185728 0.4719097
#3 0.6092747 0.15904600 0.28025778 0.3118243 0.31718216 0.1426153
#4 0.6233794 0.03999592 0.20419632 0.6218192 0.01374994 0.5442698
#5 0.8609154 0.21879954 0.13373890 0.3297702 0.23902573 0.1961747
#6 0.6403106 0.81059855 0.32568192 0.5019975 0.70649462 0.8985805

      



This means you first attach the column to the right with cbind()

and order the column sequence after that. Hope this helps.

+3


source







All Articles