如何制作现有列中唯一值的数据框?

How can I make a data frame of the unique values in an existing column?

我需要创建一个新数据框 (col.3),仅使用前一列 (col.1) 中与另一列 (col.2) 中的唯一值对应的事件在现有的数据框中。

我需要这个:

df1
col.1   col.2     
    1    1             
    1    3             
    1    7             
    1    7            
    2    12                
    2    14   
    2    14
    2    14

 df2
 col.3
     1
     1
     1
     2
     2 

我试过这个:

new.col <- cbind(df$col.1[unique(df$col.2)])

但它给我的列太长了,而且不包括完整的 col.1 值集

我怀疑 plyr 对此有一个简单的解决方案,但我还没有想出(或任何其他解决方案)。

我怎样才能达到我想要的结果?最好使用 plyr,但 base 也可以。

我们可以使用 duplicated 创建逻辑索引并使用它来对行进行子集化

df2 <- data.frame(col3. = df$col.1[!duplicated(df$col.2)])

subset

subset(df, !duplicated(col.2), select = col.1)

或使用 dplyr,在 col.2 上使用 distinct,然后 select 'col.1'

library(dplyr)
df %>%
   distinct(col.2, .keep_all = TRUE) %>%
   select(col.3 = col.1)
#  col.3
#1     1
#2     1
#3     1
#4     2
#5     2

如果根据相邻元素之间的相等性考虑重复,则使用rleid

library(data.table)
df %>% 
    filter(!duplicated(rleid(col.2))) %>% 
    select(col.3 = col.1)

如果我们转换为data.tableunique也有一个by选项

library(data.table)
unique(setDT(df), by = 'col.2')[, .(col.3 = col.1)]

数据

df <- structure(list(col.1 = c(1L, 1L, 1L, 1L, 2L, 2L, 2L), col.2 = c(1L, 
3L, 7L, 7L, 12L, 14L, 14L)), class = "data.frame", row.names = c(NA, 
-7L))