首页 > 解决方案 > R中的while循环,里面有for循环

问题描述

我有一个如下的数据框:

Col1     Col2 
   1        5
   2        6
   3        6

我想编写一个while循环来找到最小总和,在新列中为该行加1,直到新列总和为5。每次一行有一个最小值,加1。

例如:

Col1     Col2    Col1&Col2_sum     New_Value
   1        5                6             1
   2        6                8             0 
   3        6                9             0

现在将 5 添加到 col1 的第一行,因为 6 是最小值。

Col1     Col2    Col1&Col2_sum     New_Value
   6        5               11             1
   2        6                8             1 
   3        6                9             0

现在将 5 添加到第二个,因为 8 是最小值。

Col1     Col2    Col1&Col2_sum     New_Value
   6        5               11             1
   7        6               13             1 
   3        6                9             1

现在将 5 添加到第 3 个,因为 9 是最小值。

Col1     Col2    Col1&Col2_sum     New_Value
   6        5               11             2
   7        6               13             1 
   8        6               14             1

现在将 5 添加到第一个,因为 11 是最小值。(最终输出)

Col1     Col2    Col1&Col2_sum     New_Value
  11        5               16             2
   7        6               13             2 
   8        6               14             1

标签: rfor-loopwhile-loopapply

解决方案


我使用 R 进行了尝试。我之前的答案是在 Python 中。该程序看起来非常基本,因为我不是 R 程序员,但仍然尝试了一下。至少它会帮助 R 的新手(希望如此)。注意:代码可能是 R 编程方式的厌恶。

process_dframe <- function(){

    col1 = c(1, 2, 3)
    col2 = c(5, 6, 6)
    new_value = c(0, 0, 0)
    dframe <- data.frame(col1, col2, new_value)
    print(dframe)

    new_val_col_sum <- 0
    col1_increment <- 5
    size <- length(dframe$col1)
    print(size)
    while(new_val_col_sum < 5) {
        if(new_val_col_sum > 0) {
            dframe$col1[min_row] <- sum(dframe$col1[min_row], col1_increment)
        }
        min_sum <- as.integer(.Machine$integer.max)
        min_row <- 0
        for(i in 1:size) {
            crnt_sum <- sum(dframe$col1[i], dframe$col2[i])
            if(crnt_sum < min_sum) {
                min_sum <- crnt_sum
                min_row <- i
            }
        }
        dframe$new_value[min_row] <- sum(dframe$new_value[min_row], 1)
        new_val_col_sum <- sum(new_val_col_sum, 1)
    }
    return(dframe)
}

d <- process_dframe()
print(d)

输出 col1 col2 new_value 1 1 5 0 2 2 6 0 3 3 6 0 [1] 3 col1 col2 new_value 1 1 5 1 2 2 6 0 3 3 6 0 col1 col2 new_value 1 6 5 1 2 2 6 1 3 3 6 0 col1 col2 new_value 1 6 5 1 2 7 6 1 3 3 6 1 col1 col2 new_value 1 6 5 2 2 7 6 1 3 8 6 1 col1 col2 new_value 1 11 5 2 2 7 6 2 3 8 6 1


推荐阅读