5

假设我有一个像

term     cnt
apple     10
apples     5
a apple on 3
blue pears 3
pears      1

我如何过滤此列中的所有部分找到的字符串,例如得到结果

term     cnt
apple     10
pears      1

没有指出我要过滤哪些术语(苹果|梨),而是通过自引用方式(即,它确实针对整个列检查每个术语并删除部分匹配的术语)。令牌的数量没有限制,字符串的一致性也没有限制(即“mapples”将与“apple”匹配)。这将导致一个倒置的基于 dplyr 的版本

d[grep("^apple$|^pears$", d$term), ]

此外,有趣的是使用这种分离来获得累积总和,例如

term     cnt
apple     18
pears      4

我无法让它与 contains() 或 grep() 一起使用。

谢谢

4

3 回答 3

2

希望得到完整的答案。不是很地道(如 Pythonista 的调用),但有人可以建议对此进行改进:

> ssss <- data.frame(c('apple','red apple','apples','pears','blue pears'),c(15,3,10,4,3))
> 
> names(ssss) <- c('Fruit','Count')
> 
> ssss
       Fruit Count
1      apple    15
2  red apple     3
3     apples    10
4      pears     4
5 blue pears     3
> 
> root_list <- as.vector(ssss$Fruit[unlist(lapply(ssss$Fruit,function(x){length(grep(x,ssss$Fruit))>1}))])
> 
> 
> ssss %>% filter(ssss$Fruit %in% root_list)
  Fruit Count
1 apple    15
2 pears     4
> 
> data <- data.frame(lapply(root_list, function(x){y <- stringr::str_extract(ssss$Fruit,x); ifelse(is.na(y),'',y)}))
> 
> cols <- colnames(data)
> 
> #data$x <- do.call(paste0, c(data[cols]))
> #for (co in cols) data[co] <- NULL
> 
> ssss$Fruit <- do.call(paste0, c(data[cols]))
> 
> ssss %>% group_by(Fruit) %>% summarise(val = sum(Count))
# A tibble: 2 x 2
  Fruit   val
  <chr> <dbl>
1 apple    28
2 pears     7
> 
于 2017-09-15T12:56:18.493 回答
1

你可以尝试使用tidyverse类似的东西

1. define a list of the words as:

     k <- dft %>% 
          select(term) %>% 
          unlist() %>% 
          unique()

2. operate on the data as:

    dft %>%
      separate(term, c('t1', 't2')) %>%
      rowwise() %>%
      mutate( g = sum(t1 %in% k)) %>%
      filter( g > 0) %>%
      select(t1, cnt)

这使:

      t1   cnt
   <chr> <int>
1  apple    10
2 apples     5
3  pears     1

apple这仍然无法处理apples。将继续尝试。

于 2017-09-15T12:49:57.277 回答
0

试试这个:

df=data.frame(term=c('apple','apples','a apple on','blue pears','pears'),cnt=c(10,5,3,3,1))

matches = sapply(df$term,function(t,terms){grepl(pattern = t,x = terms)},df$term)

sapply(1:ncol(matches),function(t,mat){
  tempmat = mat[,t]&mat[,-t]
  indices=unlist(apply(tempmat,MARGIN = 2,which))
  df$term[indices]<<-df$term[t]
 },matches)

df%>%group_by(term)%>%summarize(cnt=sum(cnt))

 # A tibble: 2 x 2
 #  term   cnt
 #  <chr> <dbl>
 #1 apple    18
 #2 pears     4  
于 2017-09-15T14:24:58.780 回答