Search code examples
rdataframeintersectdplyr

dplyr mutate intersect not working


I have a sample data frame like this enter image description here I am trying to find the intersection between the 2 columns coauthors and nacoauthors using the following code

interscout = 
  sample_test %>% 
  mutate( commonauth = intersect( coauthors, nacoauthors) )

and I get this output enter image description here I am not sure why I am not able to get the common intersection set using intersect in mutate.

Ideally, the last row should be empty and the second row should have only JAMES M ANDERSON on intersection.

Here is the code for the structure.

> dput(sample_test)
structure(list(fname = c("JACK", "JACK", "JACK"), lname = c("SMITH", 
"SMITH", "SMITH"), cname = c("JACK  SMITH", "JACK A SMITH", "JACK B SMITH"
), coauthors = list(c("AMEY S BAILEY", "JAMES M ANDERSON"), "JAMES M ANDERSON", 
    "JOHN MURRAY"), nacoauthors = list(c("AMEY S BAILEY", "JAMES M ANDERSON"
), c("AMEY S BAILEY", "JAMES M ANDERSON"), c("AMEY S BAILEY", 
"JAMES M ANDERSON"))), row.names = c(NA, -3L), vars = list(fname, 
    lname), drop = TRUE, indices = list(0:2), group_sizes = 3L, biggest_group_size = 3L, labels = structure(list(
    fname = "JACK", lname = "SMITH"), class = "data.frame", row.names = c(NA, 
-1L), vars = list(fname, lname), drop = TRUE, .Names = c("fname", 
"lname")), class = c("grouped_df", "tbl_df", "tbl", "data.frame"
), .Names = c("fname", "lname", "cname", "coauthors", "nacoauthors"
))

Solution

  • If you add rowwise() and make your mutated column a list it'll work:

    interscout <- sample_test %>%
        ungroup() %>%
        rowwise() %>%
        mutate( commonauth = list( intersect(coauthors, nacoauthors) ) )
    

    FWIW If I don't include rowwise() I get Error: not compatible with STRSXP