r - 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
解决方案
我使用 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
推荐阅读
- python - 根据第一个元素对元组列表进行排序
- ios - 如何限制对 TextField 的输入在 SwiftUI 中仅采用 0-10 之间的数字?
- excel - 制作主工作表的副本并根据单独工作表上列表中的值对其进行命名
- node.js - 无法从 node.js 应用程序通过 SSL 连接 Elastic Search
- python - Python创建一个变量来自动存储对象信息
- r - 为什么cross() 和summarise_at() 不能识别列名
- arrays - IF 语句在两个日期之间添加数据?
- python - 相关模型 Django 的随机默认值
- python - 找到从顶部(或任意索引)开始的字典的*有序*交集的有效方法?
- ajax - Spring Validator + Ajax 显示 bindingResultErrors