I have a tibble as shown below extracted from a larger data set. I would like to sort the Species
column by alphabetical order. But for some reason beyond my understanding i cannot get this to work. Any ideas what's going on?
I tried the following methods
arrange(dummy, Species)
dummy[order(dummy$Species),]
Sample data set:
# A tibble: 4 × 3
# Groups: Species [4]
Species M mean.active.prop
<fct> <chr> <dbl>
1 Caribbean reef shark 01 1
2 Nurse shark 03 0.9
3 Lemon shark (adult) 06 0.8
4 Lemon shark (juvenile) 04 0.7
> class(dummy)
[1] "grouped_df" "tbl_df" "tbl" "data.frame"
dput output:
dummy <- structure(list(Species = structure(1:4, levels = c("Caribbean reef shark",
"Nurse shark", "Lemon shark (adult)", "Lemon shark (juvenile)",
"Tiger shark", "Great hammerhead shark", "Bull shark", "Blacktip shark",
"Southern stingray"), class = "factor"), M = c("01", "03", "06",
"04"), mean.active.prop = c(1, 0.9, 0.8, 0.7)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), groups = structure(list(
Species = structure(1:4, levels = c("Caribbean reef shark",
"Nurse shark", "Lemon shark (adult)", "Lemon shark (juvenile)",
"Tiger shark", "Great hammerhead shark", "Bull shark", "Blacktip shark",
"Southern stingray"), class = "factor"), .rows = structure(list(
1L, 2L, 3L, 4L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -4L), .drop = TRUE))
CodePudding user response:
Since you want the result in alphabetical order you need to convert Species
to character
and apply arrange
:
> dummy %>%
mutate(Species = as.character(Species)) %>%
arrange(Species)
# A tibble: 4 × 3
# Groups: Species [4]
Species M mean.active.prop
<chr> <chr> <dbl>
1 Caribbean reef shark 01 1
2 Lemon shark (adult) 06 0.8
3 Lemon shark (juvenile) 04 0.7
4 Nurse shark 03 0.9
CodePudding user response:
Species
is a factor column, it's sorted according to the underlying numeric, convert to character and you'll be able to sort just fine.
dummy
#> # A tibble: 4 × 3
#> Species M mean.active.prop
#> <fct> <chr> <dbl>
#> 1 Caribbean reef shark 01 1
#> 2 Nurse shark 03 0.9
#> 3 Lemon shark (adult) 06 0.8
#> 4 Lemon shark (juvenile) 04 0.7
levels(dummy$Species)
#> [1] "Caribbean reef shark" "Nurse shark" "Lemon shark (adult)"
#> [4] "Lemon shark (juvenile)" "Tiger shark" "Great hammerhead shark"
#> [7] "Bull shark" "Blacktip shark" "Southern stingray"
dummy[order(as.character(dummy$Species)),]
#> # A tibble: 4 × 3
#> Species M mean.active.prop
#> <fct> <chr> <dbl>
#> 1 Caribbean reef shark 01 1
#> 2 Lemon shark (adult) 06 0.8
#> 3 Lemon shark (juvenile) 04 0.7
#> 4 Nurse shark 03 0.9