Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

all group members but the current row

Tags:

r

dplyr

I've got a grouped data frame, like so:

df <- data.frame(group = rep(1:4, each=3),
                 lets = rep(LETTERS[1:4], times=3))

For each row I would now like to identify all lets within the same group other than the lets of the row itself. Using dplyr I can get all lets thus:

df %>%
  group_by(group) %>%
  mutate(all_lets_in_group = paste(lets, collapse=','))

But how do I exclude the lets of the current row from what I feed into paste()?

like image 699
RoyalTS Avatar asked Mar 30 '17 22:03

RoyalTS


1 Answers

The purpose of this task is not very clear, so the code clarity thus suffers as well, but still:

library(tidyverse)

df %>%
  group_by(group) %>%
  mutate(
    all_lets_in_group = lets %>% 
      map(function(l) setdiff(., l)) %>%
      map_chr(function(x) paste(x, collapse=',')))

Uses set operation setdiff to subtract current letter provided by purrr::map from the group's set, then reformats the list of vectors with paste and returns as character vector.

like image 157
liborm Avatar answered Oct 14 '22 03:10

liborm