Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform dataframe into list by condition in R/dplyr

I have a dataframe like this:

> df
Person    a    b    c    d
John      1    0    1    1
James     0    1    1    0
Keith     1    0    0    0
Boris     0    1    0    0
...

And I need to transform it into a list of vectors with names of elements being corresponding to column names of dataframe and elements of the list being names of persons that have 1 in a column. For the above example the list should be like this:

> result_list
$a
[1] "John" "Keith"

$b
[1] "James" "Boris"

$c
[1] "John" "James"

$d
[1] "John"

Moving on to what I know, the vector of "switched" names for every column can be obtained like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df$Person[which(df$a == 1)]

But I’m not sure how to iterate over it properly, and I think there might be a tidy solution for the task that utilizes dplyr and purrr.

>Solution :

We can reshape to ‘long’ format and split

library(dplyr)
library(tidyr)
df %>% 
    pivot_longer(cols = -Person) %>% 
    filter(value == 1) %>% 
    {split(.$Person, .$name)}

-output

$a
[1] "John"  "Keith"

$b
[1] "James" "Boris"

$c
[1] "John"  "James"

$d
[1] "John"

data

df <- structure(list(Person = c("John", "James", "Keith", "Boris"), 
    a = c(1L, 0L, 1L, 0L), b = c(0L, 1L, 0L, 1L), c = c(1L, 1L, 
    0L, 0L), d = c(1L, 0L, 0L, 0L)), class = "data.frame", row.names = c(NA, 
-4L))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading