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

Time:07-01

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)

CodePudding user response:

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),]
  • Related