How to show NA first using arrangement ()

Sample data:

temp = data.frame(col = list(NA, 1, 2, 3) ) 

Using arrange :

 temp %>% arrange(col) 

gives

  col 1 1 2 2 3 3 4 NA 

and

 temp %>% arrange(desc(col)) 

gives

  col 1 3 2 2 3 1 4 NA 

I would like to

  col 1 NA 2 3 3 2 4 1 

those. put NA first. Does anyone know how to do this?

+8
r dplyr
source share
2 answers

You can also do:

  m %>% arrange(!is.na(wt), wt) #@Spacedman dataset # mpg cyl disp hp drat wt qsec vs am gear carb #1 18.7 8 360.0 175 3.15 NA 17.02 0 0 3 2 #2 24.4 4 146.7 62 3.69 NA 20.00 1 0 4 2 #3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 #4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 #5 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 #6 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 #7 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 #8 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 #9 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 #10 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 
+24
source share

Write a function that sorts the data frame and then passes the convenient na.last=FALSE order option. My initial version can be found in the change history, David Arenburg improved it to this:

 > sortNA=function(d,n,...){d[order(d[[deparse(substitute(n))]],...),]} 

Then use like this:

 > m=mtcars[1:10,] > m$wt[5]=NA > m$wt[8]=NA > m %.% sortNA(wt, na.last=FALSE) mpg cyl disp hp drat wt qsec vs am gear carb Hornet Sportabout 18.7 8 360.0 175 3.15 NA 17.02 0 0 3 2 Merc 240D 24.4 4 146.7 62 3.69 NA 20.00 1 0 4 2 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 

Add decreasing=TRUE to sort in reverse order.

You might also consider issuing a problem for the dplyr github tracker to offer a new version of the arrange function for this.

+3
source share

All Articles