Candy Lee
Candy Lee

Reputation: 81

in R: How do you sort a matrix by rowname index?

I have merged two matrices:

library(plyr)
df3 = as.data.frame(t(combn(4,3)))    
df4 = as.data.frame(t(combn(4,4)))    
t(rbind.fill(df3,df4))

I've done transposing mainly for my benefit so I can see what I'm doing.

I would like to output:

   [,1]  [,2]  [,3] [,4] [,5]
V1    1    1    1    NA    1
V2    2    2    NA    2    2
V3    3   NA    3     3    3
V4   NA    4    4     4    4

I've tried various ways of matching/sorting/ordering but have got erroneous results. Any advice is welcome - thanks!

Upvotes: 0

Views: 52

Answers (1)

bgoldst
bgoldst

Reputation: 35314

library(plyr); ## for rbind.fill()
df3 <- as.data.frame(t(combn(4,3)));
df4 <- as.data.frame(t(combn(4,4)));
df <- t(rbind.fill(df3,df4));
apply(df,2L,function(col) col[match(seq_along(col),col)]);
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    1    1   NA    1
## [2,]    2    2   NA    2    2
## [3,]    3   NA    3    3    3
## [4,]   NA    4    4    4    4

Upvotes: 1

Related Questions