You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何删除连续重复数据并仅保留首行?R语言代码调整求助

Got it, let's figure out how to tweak that code to keep the first occurrence of consecutive duplicates instead of the last!

First, let's break down why your original code was keeping the last duplicate:

  • df$x[-1] != df$x[-nrow(df)] creates a logical vector where each entry checks if the next element is different from the current one. When you append TRUE at the end, you're telling R to keep the very last row regardless. This ends up retaining the final element of each consecutive group.

To keep the first element of each consecutive group, we need to flip the logic: we want to keep the first row, and then any row where the current element is different from the previous one. Here's the adjusted code:

df[c(TRUE, df$x[-1] != df$x[-nrow(df)]), ]

Let's test this with a quick example to make sure it works:
Suppose your data frame looks like this:

df <- data.frame(x = c(1,1,1,2,2,3,3,3,3))

Running the modified code will give you:

x
1  1
4  2
6  3

Which is exactly what you want—only the first occurrence of each consecutive duplicate group is kept.

The key change here is putting TRUE at the start of the logical vector (to always keep the first row) instead of the end. The rest of the vector checks if each subsequent element is different from the one before it, so we only keep the start of a new consecutive group.

内容的提问来源于stack exchange,提问作者S B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:47:47