【问题标题】:Reordering vectors by frequency and order of entry按频率和进入顺序重新排序向量
【发布时间】:2021-12-31 01:23:54
【问题描述】:

如何按频率和进入顺序对 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)

【问题讨论】:

    标签: r vector


    【解决方案1】:

    我们可以使用来自forcatsfct_infreqfct_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
    

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 1970-01-01
      • 2020-02-06
      • 2020-12-08
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多