henryTi
henryTi

Reputation: 131

how can I merge the rows as column next to the matrix in R?

I want to merge the rows of the data.frame next to the column? Look at the d1 and d2 please, d1 is my data.frame and output is d2 ?

d1<-data.frame(ID=c(1:3),
               Loc1=c(100,121,146))


d2<-data.frame(ID=c(1,1,2), Loc1x=c(100,100,121), 
               ID=c(2,3,4), Loc1y=c(121,146,146))

or in the another dataset,

d3<-data.frame(Samp=c("1167.p1","1187.p1" ), Chr=c("chr1", "chr2"), Loc=c(7,6) )

Upvotes: 0

Views: 35

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

Hope the code below can help a bit

do.call(
  rbind,
  c(
    make.row.names = FALSE,
    Map(
      function(z) do.call(cbind, split(z, 1:nrow(z))),
      combn(1:nrow(d1), 2, FUN = function(k) d1[k, ], simplify = FALSE)
    )
  )
)

which gives

  1.ID 1.Loc1 2.ID 2.Loc1
1    1    100    2    121
2    1    100    3    146
3    2    121    3    146

With d3, we try

do.call(
  rbind,
  c(
    make.row.names = FALSE,
    Map(
      function(z) do.call(cbind, split(z, 1:nrow(z))),
      combn(1:nrow(d3), 2, FUN = function(k) d3[k, ], simplify = FALSE)
    )
  )
)

and will get

   1.Samp 1.Chr 1.Loc  2.Samp 2.Chr 2.Loc
1 1167.p1  chr1     7 1187.p1  chr2     6

Upvotes: 1

Related Questions