Search code examples
rconcatenationpaste

Combine every three columns in R


I have a matrix like this:

df <- matrix(sample(c(0,1,1),9000,replace=T),nrow=3,ncol=3000)
df[1:3,1:9]

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] 
[1,]    1    0    1    1    1    0    1    1    0   
[2,]    1    1    1    1    1    1    1    1    0   
[3,]    0    0    1    1    0    1    0    1    1   

I want to combine every three columns so that:

        [,1] [,2] [,3] 
[1,]    101  110  110   
[2,]    111  111  110   
[3,]    001  101  011   

Any ideas?? Thank you in advance


Solution

  • We can use seq on a loop to extract every 3 columns, then paste the values by row with do.call on a data.frame

    out <- sapply(seq(1, ncol(df), by = 3), function(i)  
           do.call(paste0, as.data.frame(df[, i:(i+2)])))
    

    Or another option is to do the paste once and then split

    v1 <- do.call(paste0, as.data.frame(df))
    read.fwf(textConnection(v1), widths = rep(3, nchar(v1[1])/3), 
          colClasses = "character")
    #  V1  V2  V3  V4  V5  V6  V7  V8  V9 V10
    #1 100 010 111 111 011 011 101 111 111 011
    #2 001 101 111 101 101 111 101 111 111 111
    #3 110 011 110 001 011 101 111 101 101 111
    

    data

    df <- matrix(sample(c(0, 1, 1), 90, replace = TRUE), nrow = 3,ncol = 30)