library(tidytable)
my_dt <- tidytable(
price = c(4.5, 4.6, 4.7, 4.8, 5.1),
volume = c(0.4,1.2,0.3,8.7,6.5)
)
total = my_dt %>% summarize(total = sum(volume)) %>% pull(total)
trim = total*0.25
我想做的是找到总体积的25%的价格值.然后将这一行分成"修剪"部分和非修剪部分.所以在这个例子中,我将以如下所示的东西结束:
post_trim <- tidytable(
price = c(4.5, 4.6, 4.7, 4.8, 4.8, 5.1),
volume = c(0.4, 1.2, 0.3, 2.375, 6.325, 6.5),
trim = c(True, True, True, True, False, False)
)
我最初想到的方法是遍历rame的行,其中行将作为列表返回,并跟踪减go 数量后的余数,直到我找到余数小于体积的行:
remainder = trim
pivot = 0
for (row in my_dt){
if (remainder <= row[2]){
pivot = row[1]
break
} else {
remainder = remainder - row[2]
}
然后,我只需删除WHERE PRICE==PIVOT的行条目,并重新输入两行,一行中的体积是余数,另一行中的体积是原始的体积-余数.
我知道在行上循环通常不是一个好主意,所以我想知道我如何在不这样做的情况下完成这一点?