How Do I Change the order of the columns and rows?

I'm a newbie to this and i'm trying to create my first report but i'm struggling to get the preferred order in rows and columns. i would like the age order to be in correct order but the age 5 - 9 is randomly placed nearer the end instead of after age 0-4 years. I would also like to alter so that "All" is placed at the top of the table display rather than "Accidental Injury"
Any ideas where i'm going wrong would be most gratefully received.

Sorry i forgot to include the code and table in the above post!

raw_deaths %>%
  group_by(InjuryType, AgeGroup, Sex) %>% 
  summarise(total_deaths = sum(NumberOfDeaths)) %>%
  pivot_wider(names_from = AgeGroup, values_from = total_deaths) %>%
  as_tibble(rownames="Statistic")
  mutate(Sex = factor(Sex)) %>%
  arrange(Sex) %>%
  select(Sex, everything())
  knitr:: kable(caption = "Deaths Resulting From Unintentional Injuries in Scotland")

InjuryType

Sex

0-4 years

10-14 years

15-24 years

25-44 years

45-64 years

5-9 years

65-74 years

Accidental exposure All 4 0 32 328 1052 4 1092
Accidental exposure Female 0 0 0 76 312 0 480
Accidental exposure Male 4 0 32 252 740 4 612
All All 384 208 4184 18692 16612 208 7284
All Female 144 68 880 4296 4972 48 2732
All Male 240 140 3304 14396 11640 160 4552
Crushing All 0 0 4 4 16 0 12
Crushing Female 0 0 0 0 0 0 8
Crushing Male 0 0 4 4 16 0 4
Falls All 32 4 200 788 2596 0 2860
1-10 of 27 rows | 1-9 of 11 columns

I expect the levels are being arranged alphabetically. You can impose a certain order using the factor() function.

DF <- data.frame(Subj = c("Zoo", "All", "Accidental", "0-4", "10-15", "5-9"),
                 Value = 1:6)
DF
#>         Subj Value
#> 1        Zoo     1
#> 2        All     2
#> 3 Accidental     3
#> 4        0-4     4
#> 5      10-15     5
#> 6        5-9     6
library(dplyr, warn.conflicts = FALSE)
DF <- arrange(DF, Subj) #sort by Subj
DF
#>         Subj Value
#> 1        0-4     4
#> 2      10-15     5
#> 3        5-9     6
#> 4 Accidental     3
#> 5        All     2
#> 6        Zoo     1

#set the order of the factor levels in Subj
DF$Subj <- factor(DF$Subj, levels = c("All", "Zoo", "Accidental", "0-4", "5-9", "10-15"))
DF <- arrange(DF, Subj) #sort by Subj
DF
#>         Subj Value
#> 1        All     2
#> 2        Zoo     1
#> 3 Accidental     3
#> 4        0-4     4
#> 5        5-9     6
#> 6      10-15     5

Created on 2020-08-04 by the reprex package (v0.3.0)

Thank you so much for this response.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.