put the name of the people who have some value in some column, and group

Viewed 26

I want to put the name of the people who have some value in some column, grouping by the value to which it belongs. my df is:

name<-c("luis", "John", "Leo")
a1<-c("a","b","a")
a2<-c("b","a","b")
a3<-c(NA,"b","a")

df<-data.frame(name,a1,a2,a3)

I want to get a result like this

a1: a=c("Luis","Leo"), b="John"
a2: a="John", b=c("Luis","Leo")
a3: a="Leo", b="John" 
1 Answers

Perhaps this helps

library(dplyr)
library(tidyr)
library(collapse)
df %>% 
  pivot_longer(cols = -name, names_to = "cn", values_drop_na = TRUE) %>% 
  select(cn, value, name) %>%
  collapse::rsplit(~ cn + value)

-output

$a1
$a1$a
[1] "luis" "Leo" 

$a1$b
[1] "John"


$a2
$a2$a
[1] "John"

$a2$b
[1] "luis" "Leo" 


$a3
$a3$a
[1] "Leo"

$a3$b
[1] "John"
Related