我有一个表,其中前两行是样本标识符,第三行是距离度量,例如:
df<-data.table(H1=c(1,2,3,4,5),H2=c(7,3,2,8,9), D=c(100,4,55,66,35))我只想在两列中找到唯一的对,即1-7,2-3,4-8,5-9。删除出现在不同列中的重复的2-3和3-2对,但保留第三行(其距离对于2-3和3-2是相同的)。
发布于 2018-08-15 18:04:31
# example data
df<-data.frame(H1=c(1,2,3,4,5),
H2=c(7,3,2,8,9),
D=c(100,4,55,66,35), stringsAsFactors = F)
library(dplyr)
df %>%
rowwise() %>% # for each row
mutate(HH = paste0(sort(c(H1,H2)), collapse = ",")) %>% # create a new variable that orders and combines H1 and H2
group_by(HH) %>% # group by that variable
filter(D == max(D)) %>% # keep the row where D is the maximum (assumed logic*)
ungroup() %>% # forget the grouping
select(-HH) # remove unnecessary variable
# # A tibble: 4 x 3
# H1 H2 D
# <dbl> <dbl> <dbl>
# 1 1 7 100
# 2 3 2 55
# 3 4 8 66
# 4 5 9 35*注意:不知道从重复项中保留一行的逻辑是什么。我不得不使用一些东西作为例子,这里我保留了具有最高D值的行。如果需要,此逻辑可以更改。
https://stackoverflow.com/questions/51856550
复制相似问题