A K R
A K R

Reputation: 85

Insertion of blank columns at repetitive positions in a large data frame in R

For example,

dataX = data.frame(a=c(1:5),b=c(2:6),c=c(3:7),d=c(4:8),e=c(5:9),f=c(6:10))

How do I insert a blank column after every 2 columns?

Upvotes: 3

Views: 48

Answers (3)

lmo
lmo

Reputation: 38500

Here is a similar method that uses a trick with matrices and integer selection of columns. The original data.frame gets an NA column with cbind. The columns of this new object are then referenced with every two columns and then the final NA column using a matrix to fill in the final column with rbind.

cbind(dataX, NewCol=NA)[c(rbind(matrix(seq_along(dataX), 2), ncol(dataX)+1))]
  a b NewCol c d NewCol.1 e  f NewCol.2
1 1 2     NA 3 4       NA 5  6       NA
2 2 3     NA 4 5       NA 6  7       NA
3 3 4     NA 5 6       NA 7  8       NA
4 4 5     NA 6 7       NA 8  9       NA
5 5 6     NA 7 8       NA 9 10       NA

Upvotes: 3

akrun
akrun

Reputation: 887148

We can use use split to split the dataset at unique positions into a list of data.frame, loop through the list, cbind with NA and cbind the elements together

res <- do.call(cbind, setNames(lapply(split.default(dataX, (seq_len(ncol(dataX))-1)%/%2), 
                 function(x) cbind(x, NewCol = NA)), NULL))
res
#  a b NewCol c d NewCol e  f NewCol
#1 1 2     NA 3 4     NA 5  6     NA
#2 2 3     NA 4 5     NA 6  7     NA
#3 3 4     NA 5 6     NA 7  8     NA
#4 4 5     NA 6 7     NA 8  9     NA
#5 5 6     NA 7 8     NA 9 10     NA

names(res) <- make.unique(names(res))

Upvotes: 2

amonk
amonk

Reputation: 1795

Let us construct a empty data frame with the same number of rows as dataX

empty_df <- data.frame(x1=rep(NA,nrow(df)),x2=rep(NA,nrow(df)),x3=rep(NA,nrow(df)))
dataX<-cbind(dataX,empty_df)
dataX<-dataX[c("a","b","x1","c","d","x2","e","f","x3")]

resulting in:

   a b x1 c d x2 e  f x3
 1 1 2 NA 3 4 NA 5  6 NA
 2 2 3 NA 4 5 NA 6  7 NA
 3 3 4 NA 5 6 NA 7  8 NA
 4 4 5 NA 6 7 NA 8  9 NA
 5 5 6 NA 7 8 NA 9 10 NA

Upvotes: 0

Related Questions