0

I have a data frame like the following in R:

     V1  V2      V3      V4
 1   81 abc      goth 2014-01-01 05:54:21
 2   81 pqr  deathrock 2014-01-01 05:54:21
 3   81 pqr  goth 2014-01-01 05:54:21
 4   22 abc       80s 2014-01-01 05:54:22
 5   22 uio     retro 2014-01-01 05:54:22
 6   12 xyz     80s 2014-01-01 05:54:54
 7   81 gef      goth 2014-01-01 05:54:55
 8   22 wvy       80s 2014-01-01 05:54:22
 9   12 abc       hit 2014-01-01 05:54:54
 10  12 abc    listen 2014-01-01 05:54:54

I want to group the data frame according to column V1 first and then column V3 (all column 1 values are grouped together, and for each unique value of column 1, column 3 values are grouped together) to obtain an output like the following:

     V1  V2      V3      V4
 1   81 abc      goth 2014-01-01 05:54:21
 2   81 gef      goth 2014-01-01 05:54:55
 3   81 pqr  goth 2014-01-01 05:54:21
 4   81 pqr  deathrock 2014-01-01 05:54:21
 5   22 abc       80s 2014-01-01 05:54:22
 6   22 wvy       80s 2014-01-01 05:54:22
 7   22 uio     retro 2014-01-01 05:54:22
 8   12 xyz     80s 2014-01-01 05:54:54
 9   12 abc       hit 2014-01-01 05:54:54
 10  12 abc    listen 2014-01-01 05:54:54

How would I do it?

I have tried

 df = df %>% group_by(V1, V3) 

but it does not give the right results.

ekad
  • 13,718
  • 26
  • 42
  • 44
Asmita Poddar
  • 413
  • 1
  • 6
  • 21

2 Answers2

1

If you are only interested in ordering your dataframe use:

dfNew = df %>% %>% arrange(V1,V3) 

But if you are doing calculations by group and need to view results by order use:

dfNew = df %>% group_by(V1, V3)%>% arrange(V1,V3) 
DataTx
  • 1,579
  • 3
  • 22
  • 40
1

Try this:

df[order(df$V1, df$V3, decreasing=TRUE),]

Output:

    V1  V2        V3                  V4
 1: 81 abc      goth 2014-01-01 05:54:21
 2: 81 pqr      goth 2014-01-01 05:54:21
 3: 81 gef      goth 2014-01-01 05:54:55
 4: 81 pqr deathrock 2014-01-01 05:54:21
 5: 22 uio     retro 2014-01-01 05:54:22
 6: 22 abc       80s 2014-01-01 05:54:22
 7: 22 wvy       80s 2014-01-01 05:54:22
 8: 12 abc    listen 2014-01-01 05:54:54
 9: 12 abc       hit 2014-01-01 05:54:54
10: 12 xyz       80s 2014-01-01 05:54:54
www
  • 3,956
  • 1
  • 8
  • 22