Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reverse the order of the rows for every 'id' in data in R

I’m using R and stuck at the following problem.
I have a data called data.
data has columns including id and date.
id stands for personal id number. Within each id , there are several rows arranged by date . However, the date is ordered reversely, so I want to reverse the rows again. I don’t know how to do it. I tried to do it using group_by(id)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s an dplyr example:

library(tidyverse)
data <- tibble(id = rep(letters[1:3], each=3),
                   date = rep(as.Date(c("2022-07-01", "2022-06-25", "2022-05-15")), 3))

data %>% arrange(id, date)

# A tibble: 9 x 2
  id    date      
  <chr> <date>    
1 a     2022-05-15
2 a     2022-06-25
3 a     2022-07-01
4 b     2022-05-15
5 b     2022-06-25
6 b     2022-07-01
7 c     2022-05-15
8 c     2022-06-25
9 c     2022-07-01

Base solution without using dplyr

data[order(data$id, data$date),]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading