0

Having a dataframe:

dframe <- structure(list(id = c(1L, 1L, 1L, 1L), name = c("Amazon", "Google", 
"Google", "Yahoo"), label = c("pre", "after", "pre", "after"), 
    text_sth = c("other", "another one test text_sth another text", 
    "another text other", "another one test text_sth another text"
    )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-4L))

How is it possible to keep rows which only contains in column label pre and after for every user id detect in every name. Example of expected output:

 id name   label text_sth                                               
1 Google after another one test text_sth another text
1 Google pre   another text other  
1
  • 1
    Please clarify "for every user id detect in every name". There is only one value for id in your example data.
    – randy
    Commented Sep 28, 2019 at 22:30

3 Answers 3

3

Using tidyverse, you can apply conditions separately to groups within the data frame. We can use the filter() function combined with the fact that TRUE gets treated as 1 and FALSE as zero in some circumstances. The max() function is applied within groups.

library(tidyverse)
dframe %>%
  group_by(id, name) %>%
  filter(max(label=="pre")==1, 
         max(label=="after")==1)
2

We can use all to check if all the required values are present in the group

library(dplyr)

dframe %>%
  group_by(id, name) %>%
  filter(all(c("pre", "after") %in% label))

#     id name   label text_sth                              
#  <int> <chr>  <chr> <chr>                                 
#1     1 Google after another one test text_sth another text
#2     1 Google pre   another text other    

We can implement the same logic in base R

subset(dframe, as.logical(ave(label, id, name, FUN = function(x) 
                         all(c("pre", "after") %in% x))))  

Or two ways in data.table

library(data.table)
setDT(dframe)
dframe[dframe[, .I[all(c("pre", "after") %in% label)], by = .(id, name)]$V1]
#OR
dframe[, .SD[all(c("pre", "after") %in% label)], by = .(id, name)]
0

We can use

library(dplyr)
dframe %>%
  group_by(id, name) %>%
  filter(length(intersect(c("pre", "after"), label)) == 2)

Or use

dframe %>%
    group_by(id, name) %>%
    filter(n_distinct(label) == 2)

Or with data.table

library(data.table)
setDT(dframe)[, .SD[length(intersect(c("pre", "after"), label)) ==2], 
           .(id, name)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.