k3r0
k3r0

Reputation: 377

Reorder Rows Multiple Values

I am trying to arrange my current data set so that all the Visits are arranged for all the Individuals. I tried the method suggested in this question and it works but only shows the values for the first individual.

Data:

structure(list(Individual = c("John", "John", "John", "Anna", 
"Anna", "Anna", "Seth", "Seth", "Seth"), Visit = c("Last", "First", 
"Review", "Last", "First", "Review", "Last", "First", "Review"
), Amount = c(25, 100, 75, 25, 100, 75, 25, 100, 75)), row.names = c(NA, 
-9L), class = c("tbl_df", "tbl", "data.frame"))

Attempted code:

target <- c("First","Review","Last")
Visit <- Visit[match(target, Visit$Visit),]

Upvotes: 0

Views: 43

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

You can use :

Visit[with(Visit, order(Individual, match(Visit, target))), ]

Or using dplyr :

library(dplyr)
df %>% arrange(Individual, match(Visit, target))

#  Individual Visit  Amount
#  <chr>      <chr>   <dbl>
#1 Anna       First     100
#2 Anna       Review     75
#3 Anna       Last       25
#4 John       First     100
#5 John       Review     75
#6 John       Last       25
#7 Seth       First     100
#8 Seth       Review     75
#9 Seth       Last       25

Upvotes: 1

AnilGoyal
AnilGoyal

Reputation: 26218

I think you need conversion of Visit field into a factor field with ordering.

target <- c("First","Review","Last")
df$Visit <- factor(df$Visit, levels = target, ordered = T)

dplyr::arrange(df, Individual, Visit)

> dplyr::arrange(df, Individual, Visit)
# A tibble: 9 x 3
  Individual Visit  Amount
  <chr>      <ord>   <dbl>
1 Anna       First     100
2 Anna       Review     75
3 Anna       Last       25
4 John       First     100
5 John       Review     75
6 John       Last       25
7 Seth       First     100
8 Seth       Review     75
9 Seth       Last       25

dput used

df <- structure(list(Individual = c("John", "John", "John", "Anna", 
                                    "Anna", "Anna", "Seth", "Seth", "Seth"), Visit = c("Last", "First", 
                                                                                       "Review", "Last", "First", "Review", "Last", "First", "Review"
                                    ), Amount = c(25, 100, 75, 25, 100, 75, 25, 100, 75)), row.names = c(NA, 
                                                                                                         -9L), class = c("tbl_df", "tbl", "data.frame"))

Upvotes: 1

Related Questions