【发布时间】:2021-02-05 09:35:26
【问题描述】:
我正在寻找一种方法来遍历 R 中的数据框,删除特定条件之上的最大值,创建一个不包括该行的新数据框,重新计算值并迭代运行直到没有更多行高于特定条件 - 输出不包括删除的所有行。这是一个简单的数据集(我需要它一步一步,因为每次迭代时值都会随着我使用的数据而变化)。此示例的条件是 df$ratio > 1.9。
height <- c(100, 110, 105, 130, 160, 150, 140, 145)
bodymass <- c(60, 65, 66, 75, 90, 85, 70, 72)
df <- data.frame(height, bodymass)
df$ratio <- df$height / df$bodymass
对于这些数据,会有以下类型的迭代;
-> df$ratio <- df$height / df$bodymass
-> df$ratio > 1.9 #Condition
-> Calculate max df$ratio in df > 1.9 #first loop would remove 2.013
-> Create new df excluding that value #Now loop back to start
-> df$ratio <- df$height / df$bodymass #Recalculate (This is really important)
-> df$ratio > 1.9 #Condition
-> Calculate max df$ratio in df > 1.9 #second loop would remove 2.000
-> Create new df excluding that value #Now loop back to start
-> df$ratio <- df$height / df$bodymass #Recalculate (This is really important)
-> df$ratio > 1.9 #Condition - none left now so can exit the loop.
-> output df excluding values > 1.9.
重新计算确实是其中最重要的一步。我可以手动执行此操作没有问题,但有数千行的数据集,因此需要自动执行。任何帮助将不胜感激。 谢谢。
【问题讨论】: