根据条件R匹配和删除行

问题描述 投票:2回答:5

我为你们准备了一个有趣的东西。

我首先要查看:查看ID列并确定重复值。一旦确定了这些,代码应该通过重复值的收入并保持行具有更大的收入。

因此,如果有三个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语句来创建一个新列以识别重复项(通过子集化或不通过子集化),然后再使用新列的值来确定更大的收入。从那里我可以根据我创建的新列进行子集化。

有更快,更有效的方法吗?

结果应该是这样的。

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

谢谢

r duplicates condition subset matching
5个回答
3
投票

我们可以通过检查“收入”中按“ID”分组的最高值来slice

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

data

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))

3
投票

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

3
投票

这是另一种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)

2
投票

来自dplyr的Group_by和总结也会起作用

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.

2
投票

使用sqldf:由ID分组并选择相应的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
© www.soinside.com 2019 - 2024. All rights reserved.