删除data.frame中的行,其中包含其他列中的列

时间:2017-08-02 01:16:13

标签: r dplyr tidyverse

我正在尝试在data.frame中实现与unique类似的内容,其中一行中每列的每个元素都是向量。我想要做的是,如果该帽子行的列中的向量元素是子集或等于另一个子集,则删除具有较少元素数量的行。我可以使用嵌套的for循环来实现这一点,但由于数据包含400,000行,因此程序效率非常低。

示例数据

# Set the seed for reproducibility 
set.seed(42)

# Create a random data frame
mydf <- data.frame(items = rep(letters[1:4], length.out = 20), 
                   grps = sample(1:5, 20, replace = TRUE),
                   supergrp =  sample(LETTERS[1:4], replace = TRUE))


# Aggregate items into a single column
temp <- aggregate(items ~ grps + supergrp, mydf, unique)

# Arrange by number of items for each grp and supergroup 
indx <- order(lengths(temp$items), decreasing = T)
temp <- temp[indx, ,drop=FALSE]

Temp看起来像

       grps supergrp   items
    1     4        D a, c, d
    2     3        D    c, d
    3     5        D    a, d
    4     1        A       b
    5     2        A       b
    6     3        A       b
    7     4        A       b
    8     5        A       b
    9     1        D       d
   10     2        D       c

现在您可以看到supergrp和第二行和第三行中的项目的第二个组合包含在第一行中。所以,我想从结果中删除第二行和第三行。类似地,第5行包含在第4行中。最后,第9行和第10行包含在第一行中,因此我想删除第9行和第10行。 因此,我的结果如下:

      grps supergrp   items
    1    4        D a, c, d
    4    1        A       b 

我的实现如下::

# initialise the result dataframe by first row of old data frame
newdf <-temp[1, ]

# For all rows in the the original data
for(i in 1:nrow(temp))
{
  # Index to check if all the items are found 
  indx <- TRUE

  # Check if item in the original data appears in the new data
  for(j in 1:nrow(newdf))
  {
   if(all(c(temp$supergrp[[i]], temp$items[[i]]) %in% 
          c(newdf$supergrp[[j]], newdf$items[[j]]))){
     # set indx to false if a row with same items and supergroup  
     # as the old data is found in the new data
    indx <- FALSE
   }
  }

  # If none of the rows in new data contain items and supergroup in old data append that
  if(indx){
    newdf <- rbind(newdf, temp[i, ])
  }
}

我相信在R中有一种有效的方法可以实现这一点;可能正在使用tidy框架和dplyr链,但我错过了诀窍。对一个长期问题道歉。任何意见都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

我会尝试从列表列中获取这些项目并将它们存储在更长的数据帧中。这是我有点讨厌的解决方案:

library(stringr)

items <- temp$items %>% 
    map(~str_split(., ",")) %>% 
    map_df(~data.frame(.))

out <- bind_cols(temp[, c("grps", "supergrp")], items)

out %>% 
    gather(item_name, item, -grps, -supergrp) %>% 
    select(-item_name, -grps) %>% 
    unique() %>% 
    filter(!is.na(item))