Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.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_Dataframe - Fatal编程技术网

R 如何按向量对具有重复项的数据帧进行排序?

R 如何按向量对具有重复项的数据帧进行排序?,r,dataframe,R,Dataframe,我有一个包含两列(都包含重复项)的数据帧,我想按向量排序。这里是一个MWE: target_order <- c("a", "b", "c") df <- data.frame(col1 = c("c", "a", "b", "a", "a", "c", "c", "b"), col2 = c(1, 1, 2, 5, 4, 2, 6, 7)) 谁能帮忙?(以R为基数的解决方案会很酷。)没有给出您最终想要的输出,但可能是这样的 df[order(ma

我有一个包含两列(都包含重复项)的数据帧,我想按向量排序。这里是一个MWE:

target_order <- c("a", "b", "c")
df <- data.frame(col1 = c("c", "a", "b", "a", "a", "c", "c", "b"),
                 col2 = c(1, 1, 2, 5, 4, 2, 6, 7))

谁能帮忙?(以R为基数的解决方案会很酷。)

没有给出您最终想要的输出,但可能是这样的

df[order(match(df$col1, target_order)),]
  col1 col2
2    a    1
4    a    5
5    a    4
3    b    2
8    b    7
1    c    1
6    c    2
7    c    6

您的最终期望输出没有给出,但可能是这样的

df[order(match(df$col1, target_order)),]
  col1 col2
2    a    1
4    a    5
5    a    4
3    b    2
8    b    7
1    c    1
6    c    2
7    c    6