【问题标题】:R looping through data frame & creating new data frame iteratively using a conditionR循环遍历数据框并使用条件迭代地创建新的数据框
【发布时间】: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.

重新计算确实是其中最重要的一步。我可以手动执行此操作没有问题,但有数千行的数据集,因此需要自动执行。任何帮助将不胜感激。 谢谢。

【问题讨论】:

    标签: r dataframe loops max


    【解决方案1】:

    您可以尝试使用while循环:

    #Calculate initial ratio
    df$ratio <- df$height / df$bodymass
    
    #Continue while loop till any value is above 1.9
    while(any(df$ratio > 1.9)) {
      #Remove the row with max ratio
      df <- df[-which.max(df$ratio), ]
      #Recalculate ratio
      df$ratio <- df$height / df$bodymass
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-25
      • 2020-03-29
      • 2016-11-16
      • 2023-02-04
      • 2020-03-02
      • 2018-09-28
      • 2020-04-06
      • 1970-01-01
      相关资源
      最近更新 更多