BWolk
BWolk

Reputation: 303

Reordering rows in data frame (R)

I would like to reorder the rows in a data frame by the content of a certain column. However, when I do so the values in that column are reordered, but the corresponding values remain at the same place. To give an example:

df<- InsectSprays
df2 <- aggregate(df$count,
                        by = list(df$spray),
                        FUN = mean)
Group.1 x
A       14.500000
B       15.333333
C       2.083333
D       4.916667
E       3.500000
F       16.666667

But then if I want reorder the data, the first column is indeed reorders, but the corresponding value does not move along:

df2$Group.1 <- factor(c('B', 'D', 'A', 'C', 'E', 'F'))  

Group.1 x
B       14.500000
D       15.333333
A       2.083333
C       4.916667
E       3.500000
F       16.666667

Any ideas how to fix this?

Upvotes: 2

Views: 4482

Answers (1)

www
www

Reputation: 39154

You need to change the Group.1 column to factor. After that, you can use order to re-order the rows based on Group.1 as follows.

df2$Group.1 <- factor(df2$Group.1, levels = c('B', 'D', 'A', 'C', 'E', 'F'))

df3 <- df2[order(df2$Group.1), ]

df3
#   Group.1         x
# 2       B 15.333333
# 4       D  4.916667
# 1       A 14.500000
# 3       C  2.083333
# 5       E  3.500000
# 6       F 16.666667

DATA

df2 <- read.table(text = "Group.1 x
A       14.500000
B       15.333333
C       2.083333
D       4.916667
E       3.500000
F       16.666667",
                      header = TRUE, stringsAsFactors = FALSE)

Upvotes: 2

Related Questions