Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort a data frame manually using non numeric column

Tags:

r

i have the following data frame

    dd <- data.frame(b = c("High", "Medium", "Highest", "Low", "Not bad","Good", "V. Good"),
   x = c("C3", "C1", "C4", "N2", "C2", "N1","N4"), x = c("5", "2", "3", "6", "7", "5","7") )

so i want the data frame to be transformed using a manual order for the variable X.

for example: that's the original one

1    High C3   5
2  Medium C1   2
3 Highest C4   3
4     Low N2   6
5 Not bad C2   7
6    Good N1   5
7 V. Good N4   7

but what i want is a new data frame to begin based on the value of X but not alphabetically, but randomly in an order which i chose e.g:

the first row has x=C1, the second have x=C2, the third have x=N4, ...etc

how this can be done??

thank you

like image 336
ifreak Avatar asked Feb 22 '12 09:02

ifreak


2 Answers

Since the x column is a factor, you can simply ensure that its levels are in the order you want.

# New sorting order
desired_order <- sample(levels(dd$x))
# Re-order the levels
dd$x <- factor( as.character(dd$x), levels=desired_order )
# Re-order the data.frame
dd <- dd[order(dd$x),]
like image 170
Vincent Zoonekynd Avatar answered Nov 11 '22 08:11

Vincent Zoonekynd


If your data.frame really is small enough to manually reorder, then just make a vector of the numbers 1:7, ordered in the way that the rows should appear. e.g.:

    dd[c(2,5,7,1,4,3,6),]

    b  x x.1
    2  Medium C1   2
    5 Not bad C2   7
    7 V. Good N4   7
    1    High C3   5
    4     Low N2   6
    3 Highest C4   3
    6    Good N1   5

Or, if you really want to do it with a character vector, you can also reference by row names, like this:

    rownames(dd) <- as.character(dd$x)
    dd[c("C1","C2","N4","C3","N2","C4","N1"),]

    b  x x.1
    C1  Medium C1   2
    C2 Not bad C2   7
    N4 V. Good N4   7
    C3    High C3   5
    N2     Low N2   6
    C4 Highest C4   3
    N1    Good N1   5
like image 42
tim riffe Avatar answered Nov 11 '22 06:11

tim riffe