Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 自定义排序(非字母顺序)_R_Sorting_Categories - Fatal编程技术网

R 自定义排序(非字母顺序)

R 自定义排序(非字母顺序),r,sorting,categories,R,Sorting,Categories,我有一个分类数据集,看起来类似于: A < -data.frame(animal = c("cat","cat","cat","dog","dog","dog","elephant","elephant","elephant"), color = c(rep(c("blue","red","green"), 3))) animal color 1 cat blue 2 cat red 3 cat green 4

我有一个分类数据集,看起来类似于:

A < -data.frame(animal = c("cat","cat","cat","dog","dog","dog","elephant","elephant","elephant"),
                color = c(rep(c("blue","red","green"), 3)))

    animal color
1      cat  blue
2      cat   red
3      cat green
4      dog  blue
5      dog   red
6      dog green
7 elephant  blue
8 elephant   red
9 elephant green

应明确规定等级:

A$animal <- factor(A$animal, levels = c("dog", "elephant","cat"))
A$color <- factor(A$color, levels = c("green", "blue", "red"))

另一件值得注意的事情是,您不必转换类来实现这一点。您可以简单地按变量的因子排序。因此,如果需要的话,在现有数据结构中保留为eg字符类

例如,使用上面的例子:

A[order(factor(A$animal, levels = c("dog", "elephant","cat")) ,factor(A$color, levels = c("green", "blue", "red"))),]

这取决于阶级的保守是否重要。对于我个人来说,这将是一个更典型的用例。HTH

您也可以使用
匹配
-您既不更改列类,也不执行
因子
转换

animalOrder = c("dog", "elephant","cat")
colorOrder  = c("green", "blue", "red")
A[ order(match(A$animal, animalOrder), match(A$color, colorOrder)), ]

animal color
6      dog green
4      dog  blue
5      dog   red
9 elephant green
7 elephant  blue
8 elephant   red
3      cat green
1      cat  blue
2      cat   red
以类似的方式,我将以“tidyverse”的方式呈现订单:

A$animal <- factor(A$animal, levels = c("dog", "elephant","cat"))
A$color <- factor(A$color, levels = c("green", "blue", "red"))
或者干脆

A %>% arrange(animal, color)
其中,
%%>%%
是r中的“管道”操作符,可以通过使用
Ctrl
+
Shift
+
m

A$animal <- factor(A$animal, levels = c("dog", "elephant","cat"))
A$color <- factor(A$color, levels = c("green", "blue", "red"))
arrange(A, animal, color)
A %>% arrange(animal, color)