I have different columns A, B, C in a data frame. A has values 7,7,5 B has a,f,g, and C has 3,2,1 values. I need to sort only the values of C alphabetically leaving the whole data frame alone. I see that the order() function that let's order the entire data frame with respect to a column but I need to sort a single column.
Asked
Active
Viewed 1,669 times
0
-
If your data frame is called `df` you can do `df$C <- sort(df$C)`. This is more the kind of thing you can look up in a textbook or online than having to ask on SO. Also, `order` _can_ order a single column if you like: `df$C <- df$C[order(df$C)]` – Allan Cameron Sep 14 '20 at 11:30
-
1Does this answer your question? [How to sort a data frame in R](https://stackoverflow.com/questions/6894246/how-to-sort-a-data-frame-in-r) – Kay Sep 14 '20 at 11:48
-
@edlynch82 please see Bernhard's answer to create a reproducible example on SO. Also please add an expected output (next time) – Kay Sep 14 '20 at 11:51
-
Hey @Kay Sure! Thanks for the comment – edlynch82 Sep 14 '20 at 11:54
2 Answers
0
You can do it via sort
or via order
:
d <- data.frame(a = c(7, 7, 5), b = c("a", "f", "g"), c = c(3, 2, 1))
d$c_sorted1 <- sort(d$c)
d$c_sorted2 <- d$c[order(d$c)]

Bernhard
- 4,272
- 1
- 13
- 23
-1
As Answered by AllanCameron in the comments. Thanks to him we have got an answer.
If your data frame is called df you can do df$C <- sort(df$C). This is more the kind of thing you can look up in a textbook or online than having to ask on SO. Also, order can order a single column if you like: df$C <- df$C[order(df$C)]

edlynch82
- 1
- 3