hachiko
hachiko

Reputation: 757

R subtract min from max, second lowest from second highest etc

Is there a more efficient / better way to fun this function, either by making this function more flexible or else using a set of dplyr verbs I don't know about?

I'm taking a vector (mtcars$mpg) saving it as a variable and running it through this function - what this function does is subtracts the lowest value from the highest value and the second-lowest value from the second-highest value, etc. If length(mtcars$mpg) is odd, then it should omit the median value also, but I don't know how to incorporate that part.

vector <- function(myvector) {
  first_value <- sort(myvector)[32] - sort(myvector)[1]
  second_value <- sort(myvector)[31] - sort(myvector)[2]
  third_value <- sort(myvector)[30] - sort(myvector)[3]
  fourth_value <- sort(myvector)[29] - sort(myvector)[4]
  fifth_value <- sort(myvector)[28] - sort(myvector)[5]
  sixth_value <- sort(myvector)[27] - sort(myvector)[6]
  seventh_value <- sort(myvector)[26] - sort(myvector)[7]
  eighth_value <- sort(myvector)[25] - sort(myvector)[8]
  ninth_value <- sort(myvector)[24] - sort(myvector)[9]
  tenth_value <- sort(myvector)[23] - sort(myvector)[10]
  eleventh_value <- sort(myvector)[22] - sort(myvector)[11]
  twelfth_value <- sort(myvector)[21] - sort(myvector)[12]
  thirteenth_value <- sort(myvector)[20] - sort(myvector)[13]
  fourteenth_value <- sort(myvector)[19] - sort(myvector)[14]
  fifteenth_value <- sort(myvector)[18] - sort(myvector)[15]
  sixteenth_value <- sort(myvector)[17] - sort(myvector)[16]
  return(c(first_value, second_value, third_value, fourth_value, fifth_value, sixth_value, seventh_value, eighth_value, ninth_value, tenth_value, eleventh_value, twelfth_value, thirteenth_value, fourteenth_value, fifteenth_value, sixteenth_value))
  }

myvector <- mtcars$mpg
myvector

vector(myvector)

Upvotes: 2

Views: 169

Answers (1)

mikebader
mikebader

Reputation: 1289

Following @r2evans' sage advice and putting it into the form of a function:

maxtomin <- function(vec, N = NULL) {
    if(is.null(N)) {N <- floor(length(vec)/2)}
    vec <- sort(vec)
    vecfin <- rev(vec) - vec
    return(head(vecfin, N))
}
maxtomin(mtcars$mpg)

Upvotes: 3

Related Questions