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()
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With