This is my code:
df <- mtcars %>% rownames_to_column()
When I use group_split(rowname)
the order is change alphabetically, why?
How can I maintain the original order?
df %>% group_split(rowname)
CodePudding user response:
That's the default behaviour of group_by
which is what group_split
uses behind the scenes: arrange your variable before grouping. In this case, because it's a string, it sorts alphabetically. To keep your original order you can turn the variable into a factor:
df = df %>% mutate(rowname = factor(rowname, levels = unique(rowname)))
Output:
>[32]>
[[1]]
# A tibble: 1 × 12
rowname mpg cyl disp hp drat wt qsec vs am gear carb
<fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Mazda RX4 21 6 160 110 3.9 2.62 16.5 0 1 4 4
[[2]]
# A tibble: 1 × 12
rowname mpg cyl disp hp drat wt qsec vs am gear carb
<fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Mazda RX4 Wag 21 6 160 110 3.9 2.88 17.0 0 1 4 4
.
.
.
[[32]]
# A tibble: 1 × 12
rowname mpg cyl disp hp drat wt qsec vs am gear carb
<fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Volvo 142E 21.4 4 121 109 4.11 2.78 18.6 1 1 4 2