Sort data frame manually using non-digital column

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 converted using manual order for the variable X.

for example: what is the source

 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 I want a new data frame to start based on the value of X, but not in alphabetical order, but arbitrarily in the order I chose, for example:

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

How can I do that?

Thank you

+6
source share
2 answers

Since the x column is a factor, you can just make sure 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),] 
+10
source

If your data.frame really small enough to manually reorder, just create a 1:7 vector of numbers arranged so that the lines are displayed. eg:.

  dd[c(2,5,7,1,4,3,6),] bx 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 this with a character vector, you can also refer to string names, for example:

  rownames(dd) <- as.character(dd$x) dd[c("C1","C2","N4","C3","N2","C4","N1"),] bx 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 
0
source

Source: https://habr.com/ru/post/909060/


All Articles