I have a timeseries dataset with price variables and want to sort them. The time ist structured into quarter hours. So each group is marked by 4 rows. I want to sort the first two columns within each group. I used different codes, like order
or arrange
, but they weren't helpful. I hope someone of you, has a idea. Many thanks!
2 Answers
IIUC you want to sort your dataframe vy two variables, let's call them grp
for the grouping variable (that you say in the comment to the other answer is already sorted) and value
for the other one.
In base R you could do this:
df[order(df$grp, df$value), ]
And with dplyr
(in the tidyverse
):
library(dplyr)
df |> arrange(grp, value)
order() is a way to sort data frames, that should have worked. Consider sharing the code used--perhaps it is just a usage issue.
Another good way to sort if you're open to using to using data.table is with setkey(). For data.table you can use setkey() to sort, though it will always be ascending (unless descending setkey() ordering is ever added). For smaller datasets it doesn't much matter, but for larger datasets many operations will be faster with data.table than with data frames.
-
$\begingroup$ This is what I thought: df2 <- df1[order(df1$price1)]. And group_by(hour) before doesn't help to sort the values within each group. There must be a code, which says, that each group should be sort seperately. $\endgroup$– momoCommented Sep 6, 2022 at 14:52
-
$\begingroup$ Make the group column the first column sorted, then price1, etc., following. $\endgroup$ Commented Sep 6, 2022 at 15:23
-
$\begingroup$ Okay, thanks. But my group variable is already sorted, every group (hour) has 4 quarter hours, so the rows are numbered by 1 to 4. The main issue is to identify, how the dataset can be sorted within each group, so that the other columns and rows stay unchanged. Thanks for your help! $\endgroup$– momoCommented Sep 6, 2022 at 15:36