且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 R 中的数据框中查找重复的行(基于 2 列)

更新时间:2022-11-13 18:03:23

你总是可以尝试简单地将前两列传递给 duplicated 函数:

You can always try simply passing those first two columns to the function duplicated:

duplicated(dat[,1:2])

假设您的数据框名为 dat.有关更多信息,我们可以通过在控制台输入 ?duplicated 来查阅 duplicated 功能的帮助文件.这将提供以下句子:

assuming your data frame is called dat. For more information, we can consult the help files for the duplicated function by typing ?duplicated at the console. This will provide the following sentences:

确定向量或数据框的哪些元素是重复的具有较小下标的元素,并返回一个逻辑向量指示哪些元素(行)是重复的.

Determines which elements of a vector or data frame are duplicates of elements with smaller subscripts, and returns a logical vector indicating which elements (rows) are duplicates.

所以 duplicated 返回一个逻辑向量,然后我们可以使用它来提取 dat 的子集:

So duplicated returns a logical vector, which we can then use to extract a subset of dat:

ind <- duplicated(dat[,1:2])
dat[ind,]

或者您可以跳过单独的分配步骤并简单地使用:

or you can skip the separate assignment step and simply use:

dat[duplicated(dat[,1:2]),]