ECII
ECII

Reputation: 10629

Select a row of a dataframe and order columns in ascending or descending order in R

I have

df<-data.frame(time=c("one", "two", "three", "four", "five"), A=c(1,2,3,4,5), B=c(5,1,2,3,4), C=c(4,5,1,2,3), D=c(3,4,5,1,2), E=c(2,3,4,5,1), EF=c(1,2,3,4,5))

I would like to select for example df[df$time=="one,] and order the columns in descending order (if possible in base R and dplyr), and output a data frame. For example for df[df$time=="one,] it would be

output.one<-data.frame(time=c("one"), B=c(5), C=c(4), D=c(3), E=c(2), A=c(1))
output.one
  time B C D E A
1  one 5 4 3 2 1

and for df[df$time=="five,]

> output.five<-data.frame(time=c("five"), A=c(5), B=c(4), C=c(3), D=c(2), E=c(1))
> output.five
  time A B C D E
1 five 5 4 3 2 1

Upvotes: 0

Views: 67

Answers (2)

s_baldur
s_baldur

Reputation: 33488

Using pipes:

library(magrittr)
df %>% 
  .[.$time == "one", ] %>% 
  .[c(1, 1 + order(-.[-1]))] # "-" short for decreasing = TRUE

  time B C D E A
1  one 5 4 3 2 1

Upvotes: 1

Daniel O
Daniel O

Reputation: 4358

in Base R

order.one <- 1+order(df[df$time=="one",][(2:ncol(df))],decreasing = TRUE)
output.one <- df[df$time=="one",][c(1,order.one)]

The order can be switch to ascending by removing decreasing = TRUE

Upvotes: 1

Related Questions