使用dplyr

时间:2015-09-25 13:50:35

标签: r dplyr

我有一个如下所示的数据框:

library(dplyr)
df <- data_frame(doc.x = c("a", "b", "c", "d"),
                 doc.y = c("b", "a", "d", "c"))

所以df是:

Source: local data frame [4 x 2]

  doc.x doc.y
  (chr) (chr)
1     a     b
2     b     a
3     c     d
4     d     c

这是有序对的列表,ad,但da,依此类推。什么是类似dplyr的方法,只返回此数据框中的无序对列表?即。

  doc.x doc.y
  (chr) (chr)
1     a     b
2     c     d

3 个答案:

答案 0 :(得分:7)

使用pminpmax按字母顺序对对进行排序,即将(b,a)转换为(a,b),然后过滤掉所有重复项。

df %>%
    mutate(dx = pmin(doc.x, doc.y), dy = pmax(doc.x, doc.y)) %>%
    distinct(dx, dy) %>%
    select(-dx, -dy)
  doc.x doc.y
  (chr) (chr)
1     a     b
2     c     d

答案 1 :(得分:2)

使用data.table的替代方式:

df <- data.frame(doc.x = c("a", "b", "c", "d"),
                 doc.y = c("b", "a", "d", "c"), stringsAsFactors = F)


library(data.table)
setDT(df)
df[, row := 1:nrow(df)]
df <- df[, list(Left = max(doc.x,doc.y),Right = min(doc.x,doc.y)), by = row]
df <- df[, list(Left,Right)]
unique(df)
   Left Right
1:    b     a
2:    d     c

答案 2 :(得分:1)

使用dplyr

# make character columns into factors
df <- as.data.frame(unclass(df))
df$x.lvl <- levels(df$doc.x)
df$y.lvl <- levels(df$doc.y)

# find unique pairs
res <- df %>% 
  group_by(doc.x) %>%
  transform(x.lvl = order(doc.x), 
    y.lvl = order(doc.y)) %>%
  transform(pair = ifelse(x.lvl < y.lvl, 
        paste(doc.x, doc.y, sep=","), paste(doc.y, doc.x, sep=","))) %>%  
  .$pair %>%
  unique

唯一对

res
[1] a,b c,d
Levels: a,b c,d

修改

受Backlin的解决方案的启发,基础R

unique(with(df, paste(pmin(doc.x, doc.y), pmax(doc.x, doc.y), sep=","))
[1] "a,b" "c,d"

或存储在data.frame

unique(with(df, data.frame(lvl1=pmin(doc.x, doc.y), lvl2=pmax(doc.x, doc.y))))

  lvl1 lvl2
1    a    b
3    c    d