【问题标题】:Updating a vector using a while loop in R在 R 中使用 while 循环更新向量
【发布时间】: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 &lt;- 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 &lt;= 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


【解决方案1】:

如问题描述中所示,我不得不使用 ifelse() 而不是 if() 语句。

【讨论】:

    猜你喜欢
    • 2015-11-23
    • 2015-04-22
    • 2020-01-27
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 2021-05-24
    相关资源
    最近更新 更多