0

I have:

col 1,  col2,  col3,   col4     val
 a       b       c       d       5
 f       g       h       i       6
...

I want to rbind two columns together. I have the following:

newcol1,    newcol2
  a           b
  c           d
  f           g
  h           i
 ...
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
v_head
  • 759
  • 4
  • 13

3 Answers3

4

Here is a data.table option using rbindlist

data.table::rbindlist(split.default(df, ceiling(seq_along(df) / 2)), use.names = FALSE)

which gives

   col1 col2
1:    a    b
2:    f    g
3:    c    d
4:    h    i

Data

> dput(df)
structure(list(col1 = c("a", "f"), col2 = c("b", "g"), col3 = c("c", 
"h"), col4 = c("d", "i")), class = "data.frame", row.names = c(NA,
-2L))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
2

You can use vector recycling method to create two column dataframe.

result <- data.frame(newcol1 = unlist(df[c(TRUE, FALSE)]), 
                     newcol2 = unlist(df[c(FALSE, TRUE)]), row.names = NULL)

result

#  newcol1 newcol2
#1       a       b
#2       f       g
#3       c       d
#4       h       i

data

df <- structure(list(col1 = c("a", "f"), col2 = c("b", "g"), col3 = c("c", 
"h"), col4 = c("d", "i")), class = "data.frame", row.names = c(NA, -2L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Create example:

dd <- as.data.frame(matrix(letters[1:8], byrow=TRUE, nrow=2))
ss <- function(x) {
    ## remove data-frame structure, convert to 2x2 matrix
    m <- matrix(unlist(x),byrow=TRUE,2)
    ## set new names
    names(m) <- c("newcol1","newcol2")
    return(m)
}

Apply the function to each row and rbind() together:

rbind(ss(dd[1,]), ss(dd[2,]))
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453