简体   繁体   中英

Calculating distance between 2 elements of a data frame

I have a data frame that looks like this:

library(dplyr)
size_df <- tibble(size_chr = c("XS", "S", "M", "L", "XL", "1XL", "2XL", "3XL", "4XL", "5XL", "6XL"),
                  size_min = c(0,36,39,42,45,48,52,56,60,64,66),
                  size_max = c(36,39,42,45,48,52,56,60,64,66,70))

For any given number less than 70, I want to find the two sizes that it lies between, and the distance between them both (normalised to between 0 and 1)

For example:

input <- 37.2

# S  0.6
# M   0.4

input <- 48

# XL  1

input <- 68

# 5XL  0.5
# 6XL   0.5
INDS = c(max(1, tail(which(size_df$size_min < input), 1)),
  min(NROW(size_df), 1 + head(which(size_df$size_max > input), 1)))
size_df$size_chr[INDS]
#[1] "S" "M"

DIST = c(abs(size_df$size_min[INDS[1]] - input),
         abs(size_df$size_max[INDS[2]] - input))
DIST/sum(DIST)
#[1] 0.2 0.8

This is the perfect case for findInterval() . We'll create a vector of the breaks between categories and use those to calculate scaling factors.

size_breaks <- c(size_df[["size_min"]], max(size_df[["size_max"]]))
size_breaks
# [1]  0 36 39 42 45 48 52 56 60 64 66 70
size_spans  <- diff(size_breaks)
size_scales <- 1 / size_spans
size_scales
# [1] 0.02777778 0.33333333 0.33333333 0.33333333 0.33333333 0.25000000 0.25000000
# [8] 0.25000000 0.25000000 0.50000000 0.25000000

findInterval() will give us the index of the lower bound. The upper bound is just that index + 1.

neighbor_distances <- function(x) {
  lower <- findInterval(x, size_breaks)
  neighbors <- c(lower, lower + 1)
  distances <- abs(x - size_breaks[neighbors]) * size_scales[lower]
  tibble(
    size_chr = size_df[["size_chr"]][neighbors],
    distance = distances
  )
}

It works well for your first example.

neighbor_distances(37.2)
# # A tibble: 2 x 2
#   size_chr distance
#   <chr>       <dbl>
# 1 S           0.4  
# 2 M           0.600

The second example gives two rows instead of just one, but that can be handled with extra logic in the function. I left that logic out to keep things simple.

neighbor_distances(48)
# # A tibble: 2 x 2
#   size_chr distance
#   <chr>       <dbl>
# 1 1XL             0
# 2 2XL             1

It gives a different answer for your third example, but I don't know why you expect a number to be compared to a size category smaller than the lower bound.

neighbor_distances(68)
# # A tibble: 2 x 2
#   size_chr distance
#   <chr>       <dbl>
# 1 6XL           0.5
# 2 NA            0.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM