从R中的两个不同数据帧中选择具有两个条件的值

时间:2018-06-17 13:03:32

标签: r sorting dataframe

我收到了以下数据:

data <- structure(list(node_number = 1:8, 
                        x = c(2L, 80L, 36L, 57L, 33L, 76L, 77L, 94L 
                              ), 
                        y = c(62L, 25L, 88L, 23L, 17L, 43L, 85L, 6L 
                              ), 
                        node_demand = c(3L, 14L, 1L, 14L, 19L, 2L, 14L, 6L)), 
                   .Names = c("node_number", "x", "y", "node_demand"), 
                   class = "data.frame", row.names = c(NA, -8L))

  node_number  x  y node_demand
1           1  2 62           3
2           2 80 25          14
3           3 36 88           1
4           4 57 23          14
5           5 33 17          19
6           6 76 43           2
7           7 77 85          14
8           8 94  6           6

我需要从该列表中选择一个节点,该节点将被称为集线器,然后只要需要累积需求,就将其他节点分配为客户端。最大容量(比如30)。

要选择集线器和可用节点列表,请执行以下操作:

hubs <- data[keep <- sample(1:total_nodes, 1, replace = FALSE),]
client_nodes <- data[-keep, ]

我需要最小化与集线器及其每个客户端的距离,即我需要选择最接近集线器的客户端。

每个hub(列)到每个client(行)的距离都在此数据框中表示。

distance_df <-as.data.frame(as.matrix(round(dist(data,method = "euclidean",diag = TRUE,upper = TRUE))))

    1  2   3  4  5  6  7   8
1   0 87  43 68 57 77 79 108
2  87  0  78 23 48 22 60  26
3  43 78   0 70 73 60 43 101
4  68 23  70  0 25 30 65  42
5  57 48  73 25  0 53 81  63
6  77 22  60 30 53  0 44  41
7  79 60  43 65 81 44  0  81
8 108 26 101 42 63 41 81   0

我知道我可以使用sort()上的distance_df函数来选择最接近的函数,但我不确定如何从data聚合来自相应客户端节点的需求。

merge(data,distance_df,by=0)
  Row.names node_number  x  y node_demand   1  2   3  4  5  6  7   8
1         1           1  2 62           3   0 87  43 68 57 77 79 108
2         2           2 80 25          14  87  0  78 23 48 22 60  26
3         3           3 36 88           1  43 78   0 70 73 60 43 101
4         4           4 57 23          14  68 23  70  0 25 30 65  42
5         5           5 33 17          19  57 48  73 25  0 53 81  63
6         6           6 76 43           2  77 22  60 30 53  0 44  41
7         7           7 77 85          14  79 60  43 65 81 44  0  81
8         8           8 94  6           6 108 26 101 42 63 41 81   0

有人可以帮我一把吗?

谢谢!

0 个答案:

没有答案
相关问题