0

this may be a little simple but i cannot manage to do it !

I've got a dataframe that looks like this:

        Fruits    gr
Apples   Oranges   4   
Oranges  Lemons    5
Lemons   Apples    2 

And I want it to look like this:

        Fruits    gr
Apples   Apples     2
Oranges  Oranges    4
Lemons   Lemons     5 

So to reorder the twos columns according to the rows. Also Knowing that i have a lot of rows so i cannot move it "manually".

structure(list(Fruits = structure(1:3, .Label = c("apple", "lemons", 
"oranges"), class = "factor"), gr = c(4, 5, 2)), .Names = c("Fruits", 
"gr"), row.names = c("oranges", "apple", "lemons"), class = "data.frame")
camille
  • 16,432
  • 18
  • 38
  • 60
alpac
  • 1
  • 1
  • try typing `?sort` in the console – Wimpel Aug 13 '18 at 15:06
  • Is the first column the row name of your data.frame? It's unclear to me what's going on. It would be better if you shared your data in a [reproducible format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) (for example a `dput()` so we can see what's really there. So you seem to want to both sort rows and change row names? – MrFlick Aug 13 '18 at 15:06
  • Yes, do you want to **NOT SORT** the rownames? If not please change that. – Andre Elrico Aug 13 '18 at 15:07
  • Sorry new to R. Yes the first colum is the row names of my data.frame – alpac Aug 13 '18 at 15:08
  • Yes the rownames should not be sorted. Only the two columns. – alpac Aug 13 '18 at 15:09

1 Answers1

2

You can solve this issue like this:

df being your real data.frame.

df[]<-df[match(rownames(df),df$Fruits),]
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69
  • I don't think you need to change the rownames; the OP said in a comment they don't need rownames sorted – camille Aug 13 '18 at 15:32
  • Where does the OP say that? I'm matching the requested desired outcome. – Andre Elrico Aug 13 '18 at 15:33
  • "Yes the rownames should not be sorted. Only the two columns." Although without the second line of your solution, the rownames would have not been sorted, but would not be in their desired order. So I guess there's confusion on the OP's part or mine about rownames being unsorted vs unchanged – camille Aug 13 '18 at 15:39
  • thanks @camille your comment got me to an idea that makes my code even faster. My solution was right but a bit verbose. Like that I omit the rowname sorting and "reassigning". – Andre Elrico Aug 13 '18 at 15:41
  • 2
    Hi ! Thank you very much ! It orders perfectly my ID!! – alpac Aug 13 '18 at 17:04