0

I have 3 columns: the index of household,the number of members of each family and the number of trips for each person. How I can sort these columns?

Here is an example

  Household  person  trip
      1         1     1
      1         1     2
      1         1     3
      1         2     1
      1         2     3
      1         2     2
      2         1     2
      2         1     1
      2         2     1
      2         2     2

So I want the third column to be sorted for each person. As you can see in the first household the trips of the second person need to be sorted and in the second household for the first person

So the output is

  Household  person  trip
      1         1     1
      1         1     2
      1         1     3
      1         2     1
      1         2     2
      1         2     3
      2         1     1
      2         1     2
      2         2     1
      2         2     2
NelsonGon
  • 11,358
  • 5
  • 21
  • 44
sherek_66
  • 519
  • 4
  • 12

1 Answers1

2

An option would be to use arrange_all as there are only three columns

library(dplyr)
df1 %>%
   arrange_all
#   Household person trip
#1          1      1    1
#2          1      1    2
#3          1      1    3
#4          1      2    1
#5          1      2    2
#6          1      2    3
#7          2      1    1
#8          2      1    2
#9          2      2    1
#10         2      2    2

If there are more columns, and want to sort based on the first 3 columns

df1 %>%
   arrange_at(1:3)

can also specify the column names wrapped with vars


Or use arrange

df1 %>%
   arrange(Household, person, trip)

Or with base R

df1[do.call(order, df1[c("Household", "person", "trip")]),]

data

df1 <- structure(list(Household = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L), person = c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L), 
    trip = c(1L, 2L, 3L, 1L, 3L, 2L, 2L, 1L, 1L, 2L)), 
    class = "data.frame", row.names = c(NA, 
-10L))
akrun
  • 674,427
  • 24
  • 381
  • 486