Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

dplyr arrange() with ifelse conditional

Simple question, looking for a ‘one-liner’ -type answer, but can’t quite find what I’m looking for in other similar questions.

Want to put an ifelse() conditional inside dplyr::arrange(). Simply put: if x=1 then arrange(df,N) otherwise arrange(df,desc(N)). For completeness, x will only ever either be 1 or -1.

mwe:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x=1; df = data.frame(N=c(-5:5))

I figured arrange(df, ifelse(x==1,N,desc(N))) would work just fine but no luck. Any help?

>Solution :

ifelse is vectorized and is for vectors. It always returns a vector of the same length as the input.

For more general usage, use if(){} else{}.

arrange(df, if(x == 1) N else desc(N))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading