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:
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?
CodePudding user response:
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))