我希望根据第一列中的重复元素删除行,但也希望保留第二列。与第二列中的重复元素相关联的任何值。
输入:
df = data.frame(col1 = c("a", "a", "a", "b", "b", "c"), col2 = 1:6)预期产出:
col1 col2
a 1
b 4或,
col1 col2
a 2
b 5等。
到目前为止,使用以下命令进行了尝试,但没有保留整个数据帧:
df[(duplicated(df$col1)),] 发布于 2017-01-20 04:30:58
使用dplyr,我们可以使用group_by col1,然后只包含那些多次发生的组,并使用slice逐行获取第一行。
library(dplyr)
df %>%
group_by(col1) %>%
filter(n() > 1) %>%
slice(1)
# col1 col2
# <fctr> <int>
#1 a 1
#2 b 4从每一组中得到第二排
df %>%
group_by(col1) %>%
filter(n() > 1) %>%
slice(2)
# col1 col2
# <fctr> <int>
#1 a 2
#2 b 5我们还可以在row_number中使用dplyr函数
df %>%
group_by(col1) %>%
filter(n() > 1) %>%
filter(row_number() == 1)发布于 2017-01-20 02:53:58
以下是你想做的事:
> df = data.frame(col1 = c("a", "a", "a", "b", "b", "c"), col2 = 1:6)
> t <- table(df[,1])
> df[match(names(t[t>1]),df[,1]),]
col1 col2
1 a 1
4 b 4简短说明:table(...)计算每个元素在第一列中的次数。names(t[t>1])只选择至少出现两次的元素,而match(...)给出了所述元素的(第一个)索引。最后,选择与这些索引对应的行。
发布于 2017-01-20 03:31:13
我们可以用data.table来做这件事。将'data.frame‘转换为'data.table’(setDT(df)),按'col1‘分组,if行数大于1,得到第一行
library(data.table)
setDT(df)[, if(.N>1) head(.SD, 1) , col1]
# col1 col2
#1: a 1
#2: b 4如果我们需要第二个值
setDT(df)[, if(.N>1) .SD[2] , col1]
# col1 col2
#1: a 2
#2: b 5或者使用dplyr
library(dplyr)
df %>%
group_by(col1) %>%
filter(n()>1 & row_number()==1)
# col1 col2
# <fctr> <int>
#1 a 1
#2 b 4https://stackoverflow.com/questions/41755241
复制相似问题