Home > database >  Unique values in R using dplyr
Unique values in R using dplyr

Time:04-26

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

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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
  • Related