R Groupby column返回多列中的唯一值
这很可能是重复的-让我知道,我会删除 我有一些数据帧:R Groupby column返回多列中的唯一值,r,dataframe,grouping,R,Dataframe,Grouping,这很可能是重复的-让我知道,我会删除 我有一些数据帧: from to value sourceID targetID clustid 1 1400 1413 0.6846 3055586 3060697 1 2 323 661 0.5550 1596205 724084 1 3 323 1411 0.6817 724084 3060607 1 4 1413 1411 0.6729 3060697 3060607
from to value sourceID targetID clustid
1 1400 1413 0.6846 3055586 3060697 1
2 323 661 0.5550 1596205 724084 1
3 323 1411 0.6817 724084 3060607 1
4 1413 1411 0.6729 3060697 3060607 1
5 1498 1411 0.6381 3111960 3060607 1
6 1478 1415 0.7423 3062164 3099199 2
7 1478 1414 0.7423 3099199 3062163 2
8 1415 1462 0.7078 3090708 3062164 2
9 1415 1463 0.7078 3062164 3090709 2
10 1462 1404 0.7078 3090708 3058341 2
我想执行一个与Pythongroupby()等价的函数
来根据clustid
对数据进行分组
此外,我还想返回一个新的数据帧,其中包含sourceID
和targetID
的唯一值,并对这些值进行排序。这样,我的输出将是:
UniqueID
1 724084
1596205
3055586
3060607
3060697
3111960
2 3058341
3062163
3062164
3090708
3090709
3099199
我知道我可以使用unique()
返回sourceID
和targetID
列中所有行的唯一ID列表,如下所示:
unique_ids <- sort(unique(c((df$sourceID), (df$targetID))))
> unique_ids
[1] 370871 370873 374920 431814 612944 724084 1145838 1145839 1312582 1365467 1365468 1450552 1450553 1469099 1477137 1519842 1528881 1596205 1919812 1935866
[21] 2933725 2933726 3018082 3055586 3058341 3060607 3060697 3062163 3062164 3064884 3064885 3083388 3090708 3090709 3099199 3111960 3458397
不幸的是,这并不完全是我想要的。您可以使用
dplyr中的bind_行
快速轻松地转换到数据帧以及ID,即
dplyr::bind_rows(lapply(split(df, df$clustid),
function(i)data.frame(IDs = sort(unique(c(i$sourceID, i$targetID))))),
.id = 'cluster')
# cluster IDs
#1 1 724084
#2 1 1596205
#3 1 3055586
#4 1 3060607
#5 1 3060697
#6 1 3111960
#7 2 3058341
#8 2 3062163
#9 2 3062164
#10 2 3090708
#11 2 3090709
#12 2 3099199
下面是一个使用data.table
包的解决方案。假设您的表存储在名为df
的数据框中
df <- data.table(df)
df <- df[, list(id = unique(c(targetID, sourceID))), by = clustid]
setkeyv(df, c("clustid", "id"))
我相信使用dplyr
和tidyr
可以执行collect
操作,将两个id列合并为一个。像这样的手术
df %>%
group_by(clustid) %>%
gather(idtype, uniqueID, sourceID, targetID) %>%
arrange(uniqueID) %>%
unique() %>%
select(clustid, uniqueID) %>%
ungroup()
应该可以做到。试试lappy(分割(df,df$clustid),函数(i)排序(唯一(c(i$sourceID,i$targetID)))
在答案中添加了输出。不太对,不幸的是:/@ChuckM,这应该行得通。您使用的是不同的数据吗?谢谢。有没有办法抑制每行都有一个集群id?为什么?我想我应该在问题中提到->这些数据帧将使用formattable
或knitr
作为html表输出。支持符合这些表所需的输出格式,我希望在输出之前有一种方法可以做到。嘿,Sotos,谢谢你的回答,测试了用例,这将很好:)非常感谢,祝你有愉快的一天!我们能否以向量或列表的形式得到最终结果,其中列表的名称是ID,值是值的向量?为答案欢呼Aaron,非常感谢反馈:)
## clustid id
## 1: 1 724084
## 2: 1 1596205
## 3: 1 3055586
## 4: 1 3060607
## 5: 1 3060697
## 6: 1 3111960
## 7: 2 3058341
## 8: 2 3062163
## 9: 2 3062164
## 10: 2 3090708
## 11: 2 3090709
## 12: 2 3099199
df %>%
group_by(clustid) %>%
gather(idtype, uniqueID, sourceID, targetID) %>%
arrange(uniqueID) %>%
unique() %>%
select(clustid, uniqueID) %>%
ungroup()