【问题标题】:How to extract unique rows from a data frame with an index column?如何从具有索引列的数据框中提取唯一行?
【发布时间】:2018-11-09 09:32:40
【问题描述】:

我正在从 Excel 导入到 R,而不是重复和 Excel 的行号(索引)。如果我在设置索引之前执行 unique(),则数据框中的行位置将与 Excel 文件不对应。如果我在 Index 之后执行 unique(),它也会考虑 Index 列,并且不会有任何重复。

这个:

Index   a   b   c
1       12  12  14
2       12  12  14
3       11  12  13 

到这里:

Index   a   b   c
1       12  12  14
3       11  12  13 

代码:

library(openxlsx)
library(tidyverse)
dati <- data.table(read.xlsx("\\\\192.168.x.x\\file.xlsx", detectDates = TRUE))
#Index row
dati <- tibble::rowid_to_column(dati, "Index")

(如果是重复的问题,我很抱歉,我在高处和低处搜索了几天,没有找到任何东西。我觉得这是一个非常简单的解决方案,在不同的关键字下)

【问题讨论】:

  • 试试i &lt;- duplicated(df[-1]); df[!i, ]。也许相反的方式更具可读性,否定duplicated,而不是子集时的索引i

标签: r excel unique


【解决方案1】:

你可以使用duplicated()

> df1[-which(duplicated(df1[,-1])), ]
  Index  a  b  c
1     1 12 12 14
3     3 11 12 13

数据

df1 <- structure(list(Index = 1:3, a = c(12L, 12L, 11L), b = c(12L, 
                                                               12L, 12L), c = c(14L, 14L, 13L)), class = "data.frame", row.names = c(NA, 
                                                                                                                                     -3L))

【讨论】:

  • 非常感谢!我试图理解这段代码背后的逻辑:-which() 的意思是“不是”?而 df1[,-1] 的 -1 表示排除第一列?
  • 关闭,which() 为您提供索引(行号),- 不包括指定的行(括号内的逗号左侧)。否定“不是”是!,如果你喜欢这个,你可以这样做df1[which(!duplicated(df1[,-1])), ]
猜你喜欢
  • 2014-04-27
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
相关资源
最近更新 更多