Search code examples
rdata-analysis

How do I add 5 blank columns between every other filled column?


I have a dataframe containing N=11 variables. The X's are column names defined by R.

filenames=gtools::mixedsort(c("a1", "a10", "a11", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9"))

filenames<-data.frame(t(filenames))

list(filenames)

  X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11
1 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11

How do I insert 6 blank columns before the first filled column (a1.csv), and subsequently 5 blank columns between each of the filled columns? The output should look something like:

  X1 X2 X3 X4 X5 X6     X7 X8 X9 X10 X11 X12     X13 X14 X15 X16 X17 X18....     X67 X68 X69 X70 X71 X72

1                       a1                       a2                     ....     a11   

I need a way that can automatically perform the same operation of adding blank columns whatever the value of N.


Solution

  • A bit primitive but this should do what you want:

    library(tidyverse)
    library(stringr)
    library(gtools)
    
    filenames=gtools::mixedsort(c("a1", "a10", "a11", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9"))
    filenames <- data.frame(t(filenames)) 
    
    # Note: I am not putting filnames into a list - I use it in the form of a data frame
    
    empty_col <- data.frame(matrix(ncol = 5, nrow = nrow(filenames), data = "")) 
    
    for(i in seq_along(filenames)){ 
      filenames <- filenames %>% 
        add_column(empty_col, .before=(i + (i-1)*ncol(empty_col))) # was .after
    }
    filenames <- cbind(filenames, empty_col) # this adds 5 columns at the end since .before and .after can't be used in the same function
    
    names(filenames) <- ifelse(str_starts(names(filenames), 'X'), "", names(filenames))
    

    Result:

    1      a1      a2      a3      a4      a5      a6      a7      a8      a9      a10      a11