Home > database >  How to find first and last sections of an alphabetically sorted list in R
How to find first and last sections of an alphabetically sorted list in R

Time:10-22

how would I go about sorting a vector alphabetically and then getting the first 10 names and last 10 names printed according to the new alphabetical order?

i know to use sort(names) to get the vector in alphabetical order, and i know to use tail(names,10) and head(names,10) to get the first and last names but how to I combine these functions?

thanks for any help

CodePudding user response:

Using a small custom function you could do:

ht_sort <- function(x, n) {
  x <- sort(x)
  c(head(x, n), tail(x, n))
}

names <- rownames(mtcars)

ht_sort(names, 10)
#>  [1] "AMC Javelin"        "Cadillac Fleetwood" "Camaro Z28"        
#>  [4] "Chrysler Imperial"  "Datsun 710"         "Dodge Challenger"  
#>  [7] "Duster 360"         "Ferrari Dino"       "Fiat 128"          
#> [10] "Fiat X1-9"          "Merc 280C"          "Merc 450SE"        
#> [13] "Merc 450SL"         "Merc 450SLC"        "Pontiac Firebird"  
#> [16] "Porsche 914-2"      "Toyota Corolla"     "Toyota Corona"     
#> [19] "Valiant"            "Volvo 142E"

CodePudding user response:

Based on @stefan's answer, if you are not familiarized with functions yet, you might find this useful.

Let's say you have a vector vec. You can first sort and then combine the head and tail of your vector with c. Note that 10 tells head and tail to show 10 elements instead of the default.

vec <- rownames(mtcars)

c(head(sort(vec),10), tail(sort(vec),10))

CodePudding user response:

You simply create a function -

headtail <- function(x) { 
  y<-sort(x) 
  print(head(y))  
  print (tail(y)) 
 }

CodePudding user response:

In one go, you could do:

sort(x)[c(1:10, (length(x)-10):length(x))]

Or with sequence:

sort(x)[sequence(c(10, 10), c(1, length(x) - 10   1))]

CodePudding user response:

Using headTail from psych

library(psych)
c(headTail(sort(x), 5, ellipsis = FALSE))
  • Related