Inserting empty columns at repeated 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 an empty column after every 2 columns?

+3


source to share


3 answers


We can use split

to split the dataset at unique positions into list

of data.frame

, pass through list

, cbind

with NA

and cbind

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))

      

+2


source


Here is a similar method that uses the matrix and whole column selection trick. The original data.frame gets a NA column with cbind

. The columns of this new entity are then referenced every two columns and then the final NA column, using a matrix to populate the last 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

      

+3


source


Construct an empty data frame with the same number of lines 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")]

      

as a result:

   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

      

0


source







All Articles