Доброе утро,
У меня возникли проблемы с пониманием логики фрейма данных в R-программировании
У меня есть список городов и относительных расстояний в файле CSV с этой структурой
ВЫЕЗД; НАЗНАЧЕНИЕ; РАССТОЯНИЕ;
, где ОТПРАВЛЕНИЕ и DESTINATION имеют названия городов и DISTANCE расстояние между ними.
Пример данных
ANCONA;ASCOLIPICENO;83.0;
ANCONA;CAMPBASSO;257.0;
ANCONA;CESENA;154.0;
ANCONA;FORLI;177.0;
ANCONA;GIULIANOVA;106.0;
ANCONA;SENIGALLIA;35.0;
моя цель - получить список кортежей
ВЫЕЗД; НАЗНАЧЕНИЕ; РАССТОЯНИЕ;
, где:
- DISTANCE между DEPARTURE
- DESTINATION является наименьшим между DEPARTURE и другими городами.
- Каждый город может отображаться как ОТПРАВЛЕНИЕ один раз и как DESTINATION один раз.
Моя идея
за каждый город
- Я отмечаю как РАЗРАБОТАННЫЙ == ИСТИНА в каждой строке, в которой есть этот город как
ОТПРАВЛЕНИЕ
- Я рассчитываю наименьшее расстояние, связанное с этим отъездом
- Я читаю НАПРАВЛЕНИЕ далеко от этого ОТПРАВЛЕНИЯ с этим
высчитано РАССТОЯНИЕ
- Я сохраняю данные в одном списке
это код
#clean console
cat(c("\014"))
#trip in italian coast in Adriatic sea
fileToRead = "D:/workspaceR/prove/principiante/resources/viaggi/adriatico/adriatico.csv"
cities = read.table(header = TRUE, sep = ';', file = fileToRead)
#add ID column to dataframe, can be useful
cities$ID <- seq.int(nrow(cities))
#control the data
dim(cities)
head(cities)
#it's OK
#remove useless data
#data cleaned
#list of city, one occourrence for city
single_departure <- sort(unique(cities$DEPARTURE))
#add column ELABORATED = FALSE if not read, TRUE if it's read in elaboration
cities$ELABORATED = FALSE
#add column TO_VISIT = FALSE if it's a possibile destination, TRUE if it's a real destination
cities$TO_VISIT = FALSE
# declare final list
result <- c(nrow(single_departure))
#variable debug, using 1 city of test
flag <- TRUE #debug, using 1 city of test
#elaboration flow
for (single in single_departure) {
#debug, using 1 city of test
if (flag) {
actual_departure = (cities$DEPARTURE == single) & (!(cities$ELABORATED))
next_possible_cities = !(actual_departure)
#print(actual_departure) # dataframe of LOGICAL data
#print(single) # Correct reading of the actual departure city
smallest_distance = min(cities[actual_departure,]$DISTANCE) #return 35, , it's OK
trip <- paste(single,"->",smallest_distance); #2 contains ASCOLIPICENO -> 35, it's OK
actual_destination = cities[ next_possible_cities & cities$DISTANCE == smallest_distance, ]$DESTINATION
print((actual_destination))# why it's emtpy?? Theorically it has to be SENIGALLIA
###to run after fixing bug about destination
# trip <-paste(single, "->", actual_destination, "=", smallest_distance)
#result[single] <- trip
#cities[cities$DEPARTURE == single | cities$actual_destination == single,]$ELABORATED = TRUE
# cities[ actual_departure & cities$DISTANZA == smallest_distance & cities$actual_destination == actual_destination,]$TO_VISIT= TRUE
flag <- FALSE#debug 1 city
}#debug 1 city
}
Может быть, я все же думаю, что это логика, ориентированная на SQL, но я не понимаю, почему поднабор не находит пункт назначения города (или строку) в этой точке, но
Я могу прочитать город (или строку), когда вычисляю наименьшее расстояние.
Подскажите, пожалуйста, как обойти проблему и правильно прочитать пункт назначения?
спасибо