Sorting has been discussed quite a bit here, but I have a particular problem. I have a data frame (df) with several columns. All the observations belong to one of three types, say C1, C2, and C3. Of the various columns, one contains a value which I will call frequency (f). Example df:
Type freq Val
C3. 0.34. 10-A
C1. 0.90. 4-A
C2. 0.40. 5-B
C1. 0.65. 3-C
C2. 0.77. 5-D
C3. 0.11. 5-D
I need to sort this table so that the primary key is the Type, and secondary key is the frequency. However, and here’s my problem, they need to be sorted by a particular order of type. I need them by C1, C3, C2. So the final table looks like this:
Type freq Val
C1. 0.90. 4-A
C1. 0.65. 3-C
C3. 0.34. 10-A
C3. 0.11. 5-D
C2. 0.77. 5-D
C2. 0.40. 5-B
Is there a way to do this? To pick the particular ordering scheme of the column Type. Any suggestion is much appreciated. Thanks
1 Answer 1
We can convert the 'Type' to factor
with levels
specified in the custom order
library(dplyr)
df1 %>%
arrange(factor(Type, levels = c('C1.', 'C3.', 'C2.')), desc(freq))
# Type freq Val
#1 C1. 0.90. 4-A
#2 C1. 0.65. 3-C
#3 C3. 0.34. 10-A
#4 C3. 0.11. 5-D
#5 C2. 0.77. 5-D
#6 C2. 0.40. 5-B
Or using data.table
library(data.table)
setDT(df1)[, Type := factor(Type, levels = c('C1.', 'C3.', 'C2.'))]
setorder(df1, Type, -freq)
In base R
, we can do
df1[order(factor(df1$Type, levels = c('C1.', 'C3.', 'C2.')), -df1$freq),]
data
df1 <- structure(list(Type = c("C3.", "C1.", "C2.", "C1.", "C2.", "C3."
), freq = c("0.34.", "0.90.", "0.40.", "0.65.", "0.77.", "0.11."
), Val = c("10-A", "4-A", "5-B", "3-C", "5-D", "5-D")),
class = "data.frame", row.names = c(NA,
-6L))
-
I’m working with the "dplyr" library. My final df is arranging freq correctly, but the order of the Type is yielding C1, C2, C3, and not C1, C3, C2. I wonder if there’s something missing.Lou_A– Lou_A2020年04月06日 18:17:58 +00:00Commented Apr 6, 2020 at 18:17
-
@Orion11 If you neeed to change the column, assign the
factor
output to that column and then it should workakrun– akrun2020年04月06日 20:10:07 +00:00Commented Apr 6, 2020 at 20:10 -
1Ok. I got it to work. I was missing the "$Type" part. Thank you very much.Lou_A– Lou_A2020年04月07日 14:54:07 +00:00Commented Apr 7, 2020 at 14:54