Ahdee
Ahdee

Reputation: 4949

Rearranging column (descending/ascending) with dplyr without a prior vector

The following code can rearrange columns if one has prior knowledge of what columns are available, but what if one wants to rearrange the columns by either desc/ascending order? There are a few similar posts on StackOverflow, but not one that can do so without prior knowledge of what columns are available.

  type value
1  rna     1
2  rna     2
3  rna     3
4  dna    20
5  dna    30


d<- data.frame (type=c("rna","rna","rna"), value = c(1,2,3) )
d2 <- data.frame (type=c("dna","dna"), value = c(20,30) )
df <- rbind (d,d2)


library(dplyr)
df %>%
    group_by(type) %>%
    summarise_all(sum) %>%
    data.frame() %>%
    arrange(desc(value)) %>% # reorder row  
    select_(.dots = c("value","type") ) # reorder column

Upvotes: 2

Views: 1600

Answers (1)

CJ Yetman
CJ Yetman

Reputation: 8848

sort(names(.)) or rev(sort(names(.))) should work...

d<- data.frame (type=c("rna","rna","rna"), value = c(1,2,3) )
d2 <- data.frame (type=c("dna","dna"), value = c(20,30) )
df <- rbind (d,d2)


library(dplyr)
df %>%
  group_by(type) %>%
  summarise_all(sum) %>%
  data.frame() %>%
  arrange(desc(value)) %>% # reorder row  
  select(sort(names(.)))

Upvotes: 6

Related Questions