【发布时间】:2018-11-25 04:35:53
【问题描述】:
我得到了以下名为 nodes_df 的数据框:
x y node_demand
1 2 62 3
2 80 25 14
3 36 88 1
4 57 23 14
5 33 17 19
6 76 43 2
7 77 85 14
8 94 6 6
10 59 72 6
. . . .
. . . .
. . . .
. . . .
45 60 84 8
46 35 100 5
47 38 2 1
48 9 9 7
50 1 58 2
我必须在集线器和客户端之间拆分此 dataframe。
hubs <- nodes_df[keep <- sample(1:total_nodes, requested_hubs, replace = FALSE),]
client_nodes <- nodes_df[-keep, ]
我需要从clients_nodes中一次随机选择1行并计算总node_demand,我需要不断添加行直到random_clients$node_demand超过120。
random_clients <- client_nodes[sample(nrow(client_nodes), size = 1, replace = FALSE),]
我创建了以下变量和while循环
node_demand <- c(0)
cumulative_demand <- cumsum(node_demand)
client_nodes <- nodes_df[-keep, ]
last_node <- cumsum(cumulative_demand) >= max_supply_capacity
condition = TRUE
while(condition){
random_clients <- client_nodes[sample(nrow(client_nodes), size = 1, replace = FALSE),]
node_demand <- c(node_demand,random_clients$node_demand)
cumulative_demand <- cumsum(node_demand)
if(cumulative_demand <= max_supply_capacity){
condition == FALSE
}
}
循环没有停止,我得到以下返回值:
cumulative_demand
[1] 0 14 20 26 27 35 49 50 68 79 97 100 101 104 109 118
[17] 119 137 150 164 178 185 188 191 208 209 219 222 227 246 252 272 (it carries on and on)
我不确定为什么尽管满足cumulative_demand <= max_supply_capacity 条件,循环仍然没有停止。
谁能告诉我如何解决它?
我设法修复它:)。
我必须使用 ifelse() 以便 R 可以评估向量的条件。正常的if() 语句在这种情况下不起作用
while(TRUE){
random_clients <- client_nodes[sample(nrow(client_nodes), size = 1, replace = FALSE),]
node_demand <- c(node_demand,random_clients$node_demand)
cumulative_demand <- cumsum(node_demand)
last_node <- (cumulative_demand <= max_supply_capacity)
ifelse(last_node == FALSE,break,next)
}
【问题讨论】:
-
条件为真时while循环运行
-
谢谢!在满足逻辑条件后,我仍然没有设法打破循环。
-
condition == FALSE看起来您正在尝试比较某些东西而不是condition = FALSE。
标签: r dataframe while-loop