Используя dplyr
, мы можем получить данные в длинном формате, выбрать строки с расстоянием менее 500 и суммировать значения для каждого города.
library(dplyr)
df %>%
rownames_to_column('from') %>%
tidyr::pivot_longer(cols = -from) %>%
filter(value <= 500 & from != name) %>%
group_by(from) %>%
summarise(to = toString(name),
distance = toString(value))
# A tibble: 7 x 3
# from to distance
# <chr> <chr> <chr>
#1 BOSTON NYC, DC, PHILADELPHIA 200, 300, 200
#2 DC NYC, BOSTON, PHILADELPHIA 300, 300, 250
#3 LA SF, SANJOSE 300, 250
#4 NYC BOSTON, DC, PHILADELPHIA 200, 300, 500
#5 PHILADELPHIA NYC, BOSTON, DC 500, 200, 250
#6 SANJOSE SF, LA 400, 250
#7 SF LA, SANJOSE 300, 400
данные
df <- structure(list(NYC = c(0L, 200L, 300L, 500L, 600L, 1500L, 1800L,
2000L), BOSTON = c(200L, 0L, 300L, 200L, 700L, 1600L, 1900L,
2100L), DC = c(300L, 300L, 0L, 250L, 550L, 1400L, 1850L, 2200L
), PHILADELPHIA = c(500L, 200L, 250L, 0L, 650L, 1300L, 1700L,
1900L), CHICAGO = c(600L, 700L, 550L, 650L, 0L, 1250L, 1600L,
1500L), SF = c(1500L, 1600L, 1400L, 1300L, 1250L, 0L, 300L, 400L
), LA = c(1800L, 1900L, 1850L, 1700L, 1600L, 300L, 0L, 250L),
SANJOSE = c(2000L, 2100L, 2200L, 1900L, 1500L, 400L, 250L,
0L)), row.names = c("NYC", "BOSTON", "DC", "PHILADELPHIA",
"CHICAGO", "SF", "LA", "SANJOSE"), class = "data.frame")