user3669801 user3669801 - 4 months ago 9
R Question

Grouping rows in data frame by factor level

Lets say I have a data frame like following:

`df$A` `df$B` `df$C`
BCG 2 4
ACD 5 1
DFA 4 3
ACD 4 2
BCG 1 4
DFA 3 5
BCG 5 4


Assuming that my
df$A
is factor, how can I group the data frame rows based on factor level in
df$A
. In short, I am expecting the result like following:

`df$A` `df$B` `df$C`
BCG 2 4
BCG 1 4
BCG 5 4
ACD 5 1
ACD 4 2
DFA 4 3
DFA 3 5


Thank you for all the help.

Pj_ Pj_
Answer

Consider the following example,

dfc <- data.frame(a = rep(c('a', 'b'), 5), b = 1:10, c = 2:11)

To order dfc by the factors, you can simply perform:

dfc[order(dfc$a),]