>我有下面的数据帧:
Source<-c("DB","DB","DB","TC","TC","TC")
Drug<-c("a","a","c","d","a","c")
Target<-c("asd","asd","dch","dfg","asd","vgh")
file<-data.frame(Source,Drug,Target)
Source Drug Target
1 DB a asd
2 DB a asd
3 DB c dch
4 TC d dfg
5 TC a asd
6 TC c vgh
我的目标是创建一个数据帧 - 因此是一个csv文件 - 它将检测哪些行在2个不同的"源"之间具有相同的"药物","目标"对,并将这些行合并为一个以实现下面的形式。如果一对在"源"中存在多次 - 例如数据库中的a-asd - 不应保留两次。上面的数据帧只是一个示例,因为可能存在一对存在于 2 个以上的源中 - 例如,如果a-asd
存在于 6 个源中,那么新的合并值应该是类似于DB|TC|AD|SD|FG|FH
Source Drug Target
1 DB|TC a asd
2 DB c asd
3 TC d dfg
4 TC c vgh
fwrite(x = file22,file = 'Output.csv',na='NA')
带tidyverse
:
library(tidyverse)
file%>%
group_by(Drug,Target)%>%
summarise(Source=glue::collapse(unique(Source),"|"))
# A tibble: 4 x 3
# Groups: Drug [?]
Drug Target Source
<fct> <fct> <chr>
1 a asd DB|TC
2 c dch DB
3 c vgh TC
4 d dfg TC