R语言如何删除数据框中b最大值之后的行?
Hey there! Let's work through this together. You've got this data frame where column b first increases then decreases, and you want to keep all rows up to and including the one where b hits its maximum value (dropping everything after that). Your initial idea to find the row with the max b is spot-on—you just had the final filter logic reversed.
First, let's recap your data setup for clarity:
up <- seq(10,60,2) down <- seq(50,0,-2) df <- data.frame(time = seq(1,104,2), b = c(up, down), c = rnorm(52, 6, 3))
方法一:基于行号的直接筛选
Your first approach is totally valid once we adjust the filter. Here's how to make it work:
# 找到b达到最大值的行号 max_b_row <- which(df$b == max(df$b)) # 保留从第一行到最大值行(含)的所有数据 df_filtered <- df[1:max_b_row, ]
A quick note: if b ever had multiple identical maximum values (unlikely in your setup, but good to know), which() would return all those row numbers. If you want to stop at the first max value, use the code above. If you want to go all the way to the last occurrence of the max, tweak it to:
max_b_row <- max(which(df$b == max(df$b))) df_filtered <- df[1:max_b_row, ]
方法二:更优雅的逻辑筛选(无需行号)
Since b strictly increases then decreases, we can use the cummax() function to make this even cleaner. cummax(df$b) returns the running maximum of b as we go down the rows. So any row where b equals this running maximum is part of the increasing phase or the peak itself:
df_filtered <- df[df$b == cummax(df$b), ]
This automatically stops at the last occurrence of the maximum value, and it's concise—no need to explicitly find row numbers!
内容的提问来源于stack exchange,提问作者Strobila

