根据条件 R 匹配和删除行

Match and Remove Rows Based on Condition R

我为大家准备了一个有趣的。

我首先要查找:查看 ID 列并找出重复值。一旦确定了那些,代码应该检查重复值的收入并保留收入较大的行。

所以如果有3个ID值为2,它会寻找收入最高的那个并保留那一行。

ID Income
1 98765
2 3456
2 67
2 5498
5 23
6 98
7 5645
7 67871
9 983754
10 982
10 2374
10 875
10 4744
11 6853

我知道这就像根据条件进行子集化一样简单,但我不知道如何根据一个单元格中的收入是否大于另一个单元格来删除行。(仅当 ID 匹配时才完成)

我正在考虑使用 ifelse 语句创建一个新列来识别重复项(通过或不通过子集),然后再次使用新列的值 ifelse 来识别更大的收入。从那里我可以根据我创建的新列进行子集化。

有没有更快、更有效的方法?

结果应该是这样的。

ID Income
1 98765
2 5498
5 23
6 98
7 67871
9 983754
10 4744
11 6853

谢谢

我们可以 slice 通过检查按 'ID'

分组的 'Income' 中的最大值的行
library(dplyr)
df1 %>%
  group_by(ID) %>%
  slice(which.max(Income))

或使用data.table

library(data.table)
setDT(df1)[, .SD[which.max(Income)], by = ID]

base R

df1[with(df1, ave(Income, ID, FUN = max) == Income),]
#     ID Income
#1   1  98765
#4   2   5498
#5   5     23
#6   6     98
#8   7  67871
#9   9 983754
#13 10   4744
#14 11   6853

数据

df1 <- structure(list(ID = c(1L, 2L, 2L, 2L, 5L, 6L, 7L, 7L, 9L, 10L, 
10L, 10L, 10L, 11L), Income = c(98765L, 3456L, 67L, 5498L, 23L, 
98L, 5645L, 67871L, 983754L, 982L, 2374L, 875L, 4744L, 6853L)), 
class = "data.frame", row.names = c(NA, 
-14L))

orderduplicated(基础 R)

df=df[order(df$ID,-df$Income),]
df[!duplicated(df$ID),]
   ID Income
1   1  98765
4   2   5498
5   5     23
6   6     98
8   7  67871
9   9 983754
13 10   4744
14 11   6853

Group_by 并从 dplyr 总结也可以

df1 %>% 
  group_by(ID) %>% 
  summarise(Income=max(Income))

     ID  Income
  <int>   <dbl>
1     1  98765.
2     2   5498.
3     5     23.
4     6     98.
5     7  67871.
6     9 983754.
7    10   4744.
8    11   6853.

使用sqldf:按ID和select分组对应的max Income

library(sqldf)
sqldf("select ID,max(Income) from df group by ID")

输出:

  ID max(Income)
1  1       98765
2  2        5498
3  5          23
4  6          98
5  7       67871
6  9      983754
7 10        4744
8 11        6853

这是另一种dplyr方法。我们可以排列列,然后对第一行的数据框进行切片。

library(dplyr)

df2 <- df %>%
  arrange(ID, desc(Income)) %>%
  group_by(ID) %>%
  slice(1) %>%
  ungroup()
df2
# # A tibble: 8 x 2
#      ID Income
#   <int>  <int>
# 1     1  98765
# 2     2   5498
# 3     5     23
# 4     6     98
# 5     7  67871
# 6     9 983754
# 7    10   4744
# 8    11   6853

数据

df <- read.table(text = "ID Income
1   98765
2   3456
2   67
2   5498
5   23
6   98
7   5645
7   67871
9   983754
10  982
10  2374
10  875
10  4744
11  6853",
                 header = TRUE)