[英]How to break one column to multiple rows with each cell row limit
Thank you for your time. 感谢您的时间。
I am unable to figure out a way to perform the following operation. 我无法找出执行以下操作的方法。 The logic for the operation is to break down a column to multiple rows with limits on each cell value.
该操作的逻辑是将一列分为多个行,每个单元格值都有限制。 for 1st row and second row max is 250. subsequent are 500 max.
第一行和第二行的最大值为250。随后的最大值为500。 each value in amount should be broken down to multiple rows based on these set of rules.
根据这些规则集,每个金额值都应细分为多行。 for ex:- ID 1 has 1500 as amount.
例如:-ID 1的金额为1500。 when being broken down.
当被分解时。 the first row and second row can allow max 250 as a values.
第一行和第二行最多可允许250个值。 and next rows accommodate the rest until the amount value is maxed out.
然后下一行容纳其余部分,直到金额达到最大值。 Data is shown below
数据如下所示
Raw data 原始数据
ID Name Amount
1 aa 1500
2 bb 2000
3 cc 1000
4 dd 500
Final output 最终输出
ID Name Amount
1 aa 250
1 aa 250
1 aa 500
1 aa 500
2 bb 250
2 bb 250
2 bb 500
2 bb 500
2 bb 500
2 bb 500
3 cc 250
3 cc 250
3 cc 500
4 dd 250
4 dd 250
Here's how you could do it with loops. 这是使用循环的方法。 Won't be too bad if your data isn't too large.
如果您的数据不是太大,也不会太糟。
x = data.frame("ID"=1:5, "Name"=c("aa","bb","cc","dd","ee"),"Amount"=c(1500,2000,1000,500,800))
do_that = function(x){
y = x[0,]
r = 0
for (i in 1:NROW(x)){
count = 0
while (x[i,3] > 0){
r = r + 1
y[r,1] = x[i,1]
y[r,2] = x[i,2]
y[r,3] = 0
count = count + 1
if (count <= 2){
d = min(x[i,3], 250)
} else {
d = min(x[i,3], 500)
}
y[r,3] = y[r,3] + d
x[i,3] = x[i,3] - d
}
}
return (y)
}
y = do_that(x)
y
I even added a bonus row that's not a multiple of 250 or 500. 我什至添加了奖金行,该行不是250或500的倍数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.