Carbo
Carbo

Reputation: 916

R: create a data frame containing unique different elements across different columns of another data frame

I think it's more intuitive to show what I want to obtain with the following example. basically, for any level I want to get a list of all the elements contained in the other 3 columns without repetition.

    group1     group2       group3     Level 
    cat         cat          dog        1
    dog         parrot       cat        1
    mouse       dolphin      dolphin    1
    red         blue         blue       2
    green       yellow       green      2
    black       purple       cat        2

result I want to obtain:

var1        level
cat           1
dog           1
mouse         1
dolphin       1
Parrot        1
red           2
blue          2
green         2
purple        2
cat           2
black         2

Upvotes: 1

Views: 30

Answers (1)

akrun
akrun

Reputation: 887961

One option is to pivot into 'long' format and then get the distinct roww

library(tidyr)
library(dplyr)
df1 %>%
    pivot_longer(cols = -Level, values_to = 'var1') %>%
    distinct(Level, var1) %>%
    select(var1, level = Level)

Upvotes: 3

Related Questions