dplyr分为两列

时间:2018-08-15 09:52:56

标签: r tidyverse

我有一个表,其中前两行是样本标识符,第三行是距离度量,例如:

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的距离相同)。

1 个答案:

答案 0 :(得分:1)

# 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

*注意:不知道从重复中保留1行的逻辑。我不得不以一些示例为例,在这里,我将保留最高D值的行。如果需要,可以更改此逻辑。