按频率和进入顺序重新排序向量

Reordering vectors by frequency and order of entry

如何按频率和输入顺序对 R 中的以下向量重新排序?例如:

Z1 <- c(1,1,1,2,2) # c(1,1,1,2,2)
Z2 <- c(2,2,2,1,1) # c(1,1,1,2,2)
Z3 <- c(2,3,5,5,4) # c(2,3,1,1,4)
Z4 <- c(2,4,5,5,3) # c(2,3,1,1,4)

我试过使用 rank() 函数按如下输入顺序进行排序,但我不知道如何按频率再次对它们进行排序。有什么想法吗?

as.numeric(factor(rank(Z1))) # c(1,1,1,2,2)
as.numeric(factor(rank(Z2))) # c(2,2,2,1,1)
as.numeric(factor(rank(Z3))) # c(1,2,4,4,3)
as.numeric(factor(rank(Z4))) # c(1,3,4,4,2)

我们可以使用 fct_infreqforcats

中的 fct_inorder
> library(forcats)
> as.integer(fct_infreq(fct_inorder(as.character(Z4))))
[1] 2 3 1 1 4
> as.integer(fct_infreq(fct_inorder(as.character(Z3))))
[1] 2 3 1 1 4
> as.integer(fct_infreq(fct_inorder(as.character(Z2))))
[1] 1 1 1 2 2
> as.integer(fct_infreq(fct_inorder(as.character(Z1))))
[1] 1 1 1 2 2