我只需要使用与现有数据帧中另一列(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
一起使用,在distinct
上使用col.2
,然后在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.table
,则unique
也有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))