根据第二列删除重复项
Remove duplicates based on second column
我正在尝试编写一段代码来做一些事情:
1)按ID分组数据集
2) 计算 data.month 列中的唯一月份数
3) 删除所有少于 9 个月的 ID
4) 根据公司打印不同的 ID(即,如果与 2 家公司相关,则打印两次 ID)
5) 删除重复的 ID 并保留具有最高 data.month 编号的记录。
我的代码可以工作到 5)。我无法让我的代码只打印具有最高月份编号的重复 ID 的记录(行)。
我在这里看了几个例子:
Remove duplicates based on 2nd column condition
我知道如何删除重复项,但我无法将其应用到我的环境中。
这是我试图实现我的目标的两个代码:
data.check6 <- bind %>%
group_by(bind$ABN) %>%
summarise(count = n_distinct(data.month)) %>%
filter(count>8) %>%
rrange(bind$data.month) %>%
filter(row_number() == 1)
和:
library(tidyverse)
data.check7 <- bind %>%
group_by(ABN)%>%
filter(1 == length(unique(bind$data.month)), !duplicated(bind$data.month))
现在,我收到错误:
Error in arrange_impl(.data, dots) : incorrect size (345343) at
position 1, expecting : 3749
最后我想要一个数据集,其中每个 ID 只出现一次,并且它是与最高月份关联的 ID 记录(即列值 = 12)
我认为您正在寻找类似的东西:
示例数据:
> bind <- data.frame(ABN = rep(1:3, 3),
+ data.month = sample(1:12, 9),
+ other.inf = runif(9))
>
> bind
ABN data.month other.inf
1 1 10 0.8102867
2 2 4 0.2919716
3 3 8 0.3391790
4 1 2 0.3698933
5 2 6 0.9155280
6 3 1 0.2680165
7 1 9 0.7541168
8 2 7 0.2018796
9 3 11 0.1546079
解法:
> bind %>%
+ group_by(ABN) %>%
+ filter(data.month == max(data.month))
# A tibble: 3 x 3
# Groups: ABN [3]
ABN data.month other.inf
<int> <int> <dbl>
1 1 10 0.810
2 2 7 0.202
3 3 11 0.155
我正在尝试编写一段代码来做一些事情: 1)按ID分组数据集 2) 计算 data.month 列中的唯一月份数 3) 删除所有少于 9 个月的 ID 4) 根据公司打印不同的 ID(即,如果与 2 家公司相关,则打印两次 ID) 5) 删除重复的 ID 并保留具有最高 data.month 编号的记录。
我的代码可以工作到 5)。我无法让我的代码只打印具有最高月份编号的重复 ID 的记录(行)。
我在这里看了几个例子:
Remove duplicates based on 2nd column condition
我知道如何删除重复项,但我无法将其应用到我的环境中。
这是我试图实现我的目标的两个代码:
data.check6 <- bind %>%
group_by(bind$ABN) %>%
summarise(count = n_distinct(data.month)) %>%
filter(count>8) %>%
rrange(bind$data.month) %>%
filter(row_number() == 1)
和:
library(tidyverse)
data.check7 <- bind %>%
group_by(ABN)%>%
filter(1 == length(unique(bind$data.month)), !duplicated(bind$data.month))
现在,我收到错误:
Error in arrange_impl(.data, dots) : incorrect size (345343) at position 1, expecting : 3749
最后我想要一个数据集,其中每个 ID 只出现一次,并且它是与最高月份关联的 ID 记录(即列值 = 12)
我认为您正在寻找类似的东西:
示例数据:
> bind <- data.frame(ABN = rep(1:3, 3),
+ data.month = sample(1:12, 9),
+ other.inf = runif(9))
>
> bind
ABN data.month other.inf
1 1 10 0.8102867
2 2 4 0.2919716
3 3 8 0.3391790
4 1 2 0.3698933
5 2 6 0.9155280
6 3 1 0.2680165
7 1 9 0.7541168
8 2 7 0.2018796
9 3 11 0.1546079
解法:
> bind %>%
+ group_by(ABN) %>%
+ filter(data.month == max(data.month))
# A tibble: 3 x 3
# Groups: ABN [3]
ABN data.month other.inf
<int> <int> <dbl>
1 1 10 0.810
2 2 7 0.202
3 3 11 0.155