Insert an empty column between each column of the dataframe in R

Let's say you have a four-column data frame:

dat <- data.frame(A = rnorm(5), B = rnorm(5), C = rnorm(5), D = rnorm(5))

      

And you want to insert an empty column between each of the columns in the dataframe, so the output is:

           A A1           B B1          C C1           D D1
1 1.15660588 NA  0.78350197 NA -0.2098506 NA  2.07495662 NA
2 0.60107853 NA  0.03517539 NA -0.4119263 NA -0.08155673 NA
3 0.99680981 NA -0.83796981 NA  1.2742644 NA  0.67469277 NA
4 0.09940946 NA -0.89804952 NA  0.3419173 NA -0.95347049 NA
5 0.28270734 NA -0.57175554 NA -0.4889045 NA -0.11473839 NA

      

How do you do it?

The data core I would like to do for this operation contains hundreds of columns, and so obviously I don't want to print each column and add them naively like this:

dat$A1 <- NA
dat$B1 <- NA
dat$C1 <- NA
dat$D1 <- NA

dat <- dat[, c("A", "A1", "B", "B1", "C", "C1", "D", "D1")]

      

Thanks for the help!

+3


source to share


3 answers


You may try

 res <- data.frame(dat, dat*NA)[order(rep(names(dat),2))]
 res     
 #           A A.1           B B.1          C C.1           D D.1
 #1 1.15660588  NA  0.78350197  NA -0.2098506  NA  2.07495662  NA
 #2 0.60107853  NA  0.03517539  NA -0.4119263  NA -0.08155673  NA
 #3 0.99680981  NA -0.83796981  NA  1.2742644  NA  0.67469277  NA
 #4 0.09940946  NA -0.89804952  NA  0.3419173  NA -0.95347049  NA
 #5 0.28270734  NA -0.57175554  NA -0.4889045  NA -0.11473839  NA

      

NOTE. I am leaving .

in the column names as it is a trivial task to remove it.



Or another option

dat[paste0(names(dat),1)] <- NA
dat[order(names(dat))]

      

+7


source


you can try this



df <- cbind(dat, dat)
df <- df[, sort(names(df))]
df[, seq(2, 8,by=2)] <- NA
names(df) <- sub("\\.", "", names(df))

      

+2


source


# create new data frame with twice the number of columns
bigdat <- data.frame(matrix(ncol = dim(dat)[2]*2, nrow = dim(dat)[1]))

# set sequence of target column indices
inds <- seq(1,dim(bigdat)[2],by=2)

# insert values
bigdat[,inds] <- dat

# set column names
colnames(bigdat)[inds] <- colnames(dat)

      

0


source







All Articles