dput(data) structure(list(Country = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2-6ren">
gpt4 book ai didi

r - 仅保留元素数量最多的 "cluster"

转载 作者:行者123 更新时间:2023-12-04 09:47:57 24 4
gpt4 key购买 nike

从示例数据开始:

> dput(data)
structure(list(Country = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L), .Label = c("France", "Spain"), class = "factor"),
Car = structure(c(6L, 17L, 7L, 18L, 4L, 13L, 20L, 5L, 14L,
21L, 8L, 11L, 15L, 9L, 12L, 16L, 8L, 11L, 15L, 9L, 12L, 19L,
3L, 10L, 1L, 2L), .Label = c("Audi_1_EON", "Audi_2_EON",
"Ferrari_1_EOD", "Fiat_1_EOD", "Fiat_1_EON", "Mazda_1_EOD",
"Mazda_1_EON", "Mercedes_1_EOD", "Mercedes_1_EON", "Mercedes_2_EOD",
"Nexia_1_EOD", "Nexia_1_EON", "Opel_1_EOD", "Opel_1_EON",
"Peugeot_1_EOD", "Peugeot_1_EON", "Porsche_2_EOD", "Porsche_2_EON",
"Tico_1_EON", "VW_1_EOD", "VW_1_EON"), class = "factor"),
ValueOfComp = c(13L, 13L, 13L, 13L, 14L, 14L, 14L, 14L, 14L,
14L, 15L, 15L, 15L, 15L, 15L, 15L, 16L, 16L, 16L, 16L, 16L,
16L, 12L, 12L, 12L, 12L)), .Names = c("Country", "Car", "ValueOfComp"
), class = "data.frame", row.names = c(NA, -26L))

在所提供的数据中,我们的第一列中有两个不同的国家/地区。在下一列中,我们可以找到分配给每个国家/地区的汽车,最后一列是集群数量。

我想在表中只为每个国家/地区保留一个集群。它必须是每个国家最大的集群。我们以法国为例。两个集群(1314)分配给该国家/地区。很明显,集群 14 包含更多元素/汽车。在这种情况下,我想保留簇 14 并从数据中删除簇 13。

所提供的数据仅是示例。我的真实数据是一张巨大的表,因此我相信在某些情况下,簇可能包含相同数量的元素,因此哪个元素保留在数据中并不重要。

最佳答案

library(data.table)

data[ValueOfComp %in% setDT(data)[,rle(ValueOfComp), Country][
,values[which.max(lengths)], Country]$V1,]

Country Car ValueOfComp
1: France Fiat_1_EOD 14
2: France Opel_1_EOD 14
3: France VW_1_EOD 14
4: France Fiat_1_EON 14
5: France Opel_1_EON 14
6: France VW_1_EON 14
7: Spain Mercedes_1_EOD 15
8: Spain Nexia_1_EOD 15
9: Spain Peugeot_1_EOD 15
10: Spain Mercedes_1_EON 15
11: Spain Nexia_1_EON 15
12: Spain Peugeot_1_EON 15

关于r - 仅保留元素数量最多的 "cluster",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36736012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com