'Unique values in R using dplyr

starwars %>%
     group_by(species,sex) %>%
     summarise() %>%
     select(unique.species=species, unique.sex=sex) 

How to get unique values from 2 columns("species","sex") all together? I wrote the code above but i'm not sure it's right. Thank you



Solution 1:[1]

library(tidyverse)

starwars |> 
  select(species, sex) |> 
  distinct() 
#> # A tibble: 41 × 2
#>    species        sex           
#>    <chr>          <chr>         
#>  1 Human          male          
#>  2 Droid          none          
#>  3 Human          female        
#>  4 Wookiee        male          
#>  5 Rodian         male          
#>  6 Hutt           hermaphroditic
#>  7 Yoda's species male          
#>  8 Trandoshan     male          
#>  9 Mon Calamari   male          
#> 10 Ewok           male          
#> # … with 31 more rows

Created on 2022-04-25 by the reprex package (v2.0.1)

Solution 2:[2]

library(tidyverse)

starwars %>% 
  expand(nesting(species, sex))
#> # A tibble: 41 × 2
#>    species   sex   
#>    <chr>     <chr> 
#>  1 Aleena    male  
#>  2 Besalisk  male  
#>  3 Cerean    male  
#>  4 Chagrian  male  
#>  5 Clawdite  female
#>  6 Droid     none  
#>  7 Dug       male  
#>  8 Ewok      male  
#>  9 Geonosian male  
#> 10 Gungan    male  
#> # … with 31 more rows

Created on 2022-04-25 by the reprex package (v2.0.1)

Solution 3:[3]

There are multiple options. You can use the following code:

unique(starwars[c("species", "sex")])

Output:

   species        sex           
   <chr>          <chr>         
 1 Human          male          
 2 Droid          none          
 3 Human          female        
 4 Wookiee        male          
 5 Rodian         male          
 6 Hutt           hermaphroditic
 7 Yoda's species male          
 8 Trandoshan     male          
 9 Mon Calamari   male          
10 Ewok           male          
# … with 31 more rows

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Carl
Solution 2 Yuriy Saraykin
Solution 3 Quinten