【问题标题】:Tell which rows are distinct while keeping the ID variable告诉哪些行是不同的,同时保持 ID 变量
【发布时间】:2018-09-18 12:49:47
【问题描述】:

我有一个包含 1,000 多列和数十万行的 tibble。我想摆脱重复值,同时为每一行保留唯一的 ID 值。这是我尝试使用 mtcars 的简化版本。

library(tidyverse)

mtcars %>% 
  as_tibble() %>% 
  rownames_to_column() %>% 
  distinct(mpg:carb, .keep_all = TRUE)

#Error in mutate_impl(.data, dots) : 
#  Column `mpg:carb` must be length 32 (the number of rows) or one, not 18
#In addition: Warning messages:
#1: In mpg:carb : numerical expression has 32 elements: only the first used
#2: In mpg:carb : numerical expression has 32 elements: only the first used

任何想法如何在保留 ID 变量的同时删除非唯一行?在 mtcars 示例中,ID 变量是 rownames。列太多,我无法单独键入。

【问题讨论】:

  • 顺便说一句,我什至不确定 mtcars 是否有任何重复项...将来,请尝试使用更简单的示例,例如:dd<-data.frame(a=c("a","b","c","d","e","f"), b=c(1,1:5), c=c(1,1,3,2,4,5))

标签: r dplyr


【解决方案1】:
df_filtered<-df[!duplicated(df[,-1]),]

(假设 ID 列是第一个)。 它的作用是为您提供数据框的子集 (df),其中仅包含除第一列之外的整行不与前一行重复的那些行。

【讨论】:

    猜你喜欢
    • 2014-08-27
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多